Qt Quick Controls - Chat Tutorial#

Tutorial about writing a basic chat client using Qt Quick Controls.

This tutorial shows how to write a basic chat application using Qt Quick Controls. It will also explain how to integrate an SQL database into a Qt application.

Chapter 1: Setting Up#

When setting up a new project, it’s easiest to use Qt Creator. For this project, we chose the Qt Quick application template, which creates a basic “Hello World” application with the following files:

  • MainForm.ui.qml - Defines the default UI

  • main.qml - Embeds the default UI in a Window

  • qml.qrc - Lists the .qml files that are built into the binary

  • main.cpp - Loads main.qml

  • chattutorial.pro - Provides the qmake configuration


Delete the MainForm.ui.qml and qml.qrc files from the project, as we will not use them in this tutorial.


The default code in main.cpp has two includes:

The first gives us access to QGuiApplication. All Qt applications require an application object, but the precise type depends on what the application does. QCoreApplication is sufficient for non-graphical applications. QGuiApplication is sufficient for graphical applications that do not use Qt Widgets, while QApplication is required for those that do.

The second include makes QQmlApplicationEngine available, along with some useful functions required for making C++ types accessible from QML.

Within main(), we set up the application object and QML engine:

It begins with enabling high DPI scaling, which is not part of the default code. It is necessary to do so before the application object is constructed.

After that’s done, we construct the application object, passing any application arguments provided by the user.

Next, the QML engine is created. QQmlApplicationEngine is a convenient wrapper over QQmlEngine, providing the load() function to easily load QML for an application. It also adds some convenience for using file selectors .

Once we’ve set up things in C++, we can move on to the user interface in QML.


Let’s modify the default QML code to suit our needs.

First, import the Qt Quick module. This gives us access to graphical primitives such as Item, Rectangle, Text, and so on. For the full list of types, see the Qt Quick QML Types documentation.

Next, import the Qt Quick Controls module. Amongst other things, this provides access to ApplicationWindow , which will replace the existing root type, Window:


ApplicationWindow is a Window with some added convenience for creating a header and a footer . It also provides the foundation for popups and supports some basic styling, such as the background color.

There are three properties that are almost always set when using ApplicationWindow : width, height, and visible. Once we’ve set these, we have a properly sized, empty window ready to be filled with content.


The title property from the default code is removed.

The first “screen” in our application will be a list of contacts. It would be nice to have some text at the top of each screen that describes its purpose. The header and footer properties of ApplicationWindow could work in this situation. They have some characteristics that make them ideal for items that should be displayed on every screen of an application:

  • They are anchored to the top and bottom of the window, respectively.

  • They fill the width of the window.

However, when the contents of the header and footer varies depending on which screen the user is viewing, it is much easier to use Page . For now, we’ll just add one page, but in the next chapter, we’ll demonstrate how to navigate between several pages.

We replace the default MainForm {...} code block with a Page, which is sized to occupy all the space on the window using the anchors.fill property.

Then, we assign a Label to its header property. Label extends the primitive Text item from the Qt Quick module by adding styling and font inheritance. This means that a Label can look different depending on which style is in use, and can also propagate its pixel size to its children.

We want some distance between the top of the application window and the text, so we set the padding property. This allocates extra space on each side of the label (within its bounds). We can also explicitly set the topPadding and bottomPadding properties instead.

We set the text of the label using the qsTr() function, which ensures that the text can be translated by Qt’s translation system. It’s a good practice to follow for text that is visible to the end users of your application.

By default, text is vertically aligned to the top of its bounds, while the horizontal alignment depends on the natural direction of the text; for example, text that is read from left to right will be aligned to the left. If we used these defaults, our text would be at the top-left corner of the window. This is not desirable for a header, so we align the text to the center of its bounds, both horizontally and vertically.

The Project File#

The .pro or project file contains all of the information needed by qmake to generate a Makefile, which is then used to compile and link the application.

The first line tells qmake which kind of project this is. We’re building an application, so we use the app template.

The next line declares the Qt libraries that we want to use from C++.

This line states that a C++11 compatible compiler is required to build the project.

The SOURCES variable lists all of the source files that should be compiled. A similar variable, HEADERS, is available for header files.

The next line tells qmake that we have a collection of resources that should be built into the executable.

This line replaces deployment settings that come with the default project file. It determines where the example is copied, on running “make install".

Now we can build and run the application:


Chapter 2: Lists#

In this chapter, we’ll explain how to create a list of interactive items using ListView and ItemDelegate .

ListView comes from the Qt Quick module, and displays a list of items populated from a model. ItemDelegate comes from the Qt Quick Controls module, and provides a standard view item for use in views and controls such as ListView and ComboBox . For example, each ItemDelegate can display text, be checked on and off, and react to mouse clicks.

Here is our ListView:


Sizing and Positioning#

The first thing we do is set a size for the view. It should fill the available space on the page, so we use anchors.fill. Note that Page ensures that its header and footer have enough of their own space reserved, so the view in this case will sit below the header, for example.

Next, we set margins around the ListView to put some distance between it and the edges of the window. The margin properties reserve space within the bounds of the view, which means that the empty areas can still be “flicked” by the user.

The items should be nicely spaced out within the view, so the spacing property is set to 20.


In order to quickly populate the view with some items, we’ve used a JavaScript array as the model. One of the greatest strengths of QML is its ability to make prototyping an application extremely quick, and this is an example of that. It’s also possible to simply assign a number to the model property to indicate how many items you need. For example, if you assign 10 to the model property, each item’s display text will be a number from 0 to 9.

However, once the application gets past the prototype stage, it quickly becomes necessary to use some real data. For this, it’s best to use a proper C++ model by subclassing QAbstractItemModel.


On to the delegate. We assign the corresponding text from the model to the text property of ItemDelegate . The exact manner in which the data from the model is made available to each delegate depends on the type of model used. See Models and Views in Qt Quick for more information.

In our application, the width of each item in the view should be the same as the width of the view. This ensures that the user has a lot of room with which to select a contact from the list, which is an important factor on devices with small touch screens, like mobile phones. However, the width of the view includes our 48 pixel margins, so we must account for that in our assignment to the width property.

Next, we define an Image. This will display a picture of the user’s contact. The image will be 40 pixels wide and 40 pixels high. We’ll base the height of the delegate on the image’s height, so that we don’t have any empty vertical space.


Chapter 3: Navigation#

In this chapter, you’ll learn how to use StackView to navigate between pages in an application. Here’s the revised main.qml:

Chapter 4: Models#

In chapter 4, we’ll take you through the process of creating both read-only and read-write SQL models in C++ and exposing them to QML to populate views.


In order to keep the tutorial simple, we’ve chosen to make the list of user contacts non-editable. QSqlQueryModel is the logical choice for this purpose, as it provides a read-only data model for SQL result sets.

Let’s take a look at our SqlContactModel class that derives from QSqlQueryModel:

There’s not much going on here, so let’s move on to the .cpp file:

We include the header file of our class and those that we require from Qt. We then define a static function named createTable() that we’ll use to create the SQL table (if it doesn’t already exist), and then populate it with some dummy contacts.

The call to database() might look a little bit confusing because we have not set up a specific database yet. If no connection name is passed to this function, it will return a “default connection”, whose creation we will cover soon.

In the constructor, we call createTable(). We then construct a query that will be used to populate the model. In this case, we are simply interested in all rows of the Contacts table.


SqlConversationModel is more complex:

We use both the Q_PROPERTY and Q_INVOKABLE macros, and therefore we must let moc know by using the Q_OBJECT macro.

The recipient property will be set from QML to let the model know which conversation it should retrieve messages for.

We override the data() and roleNames() functions so that we can use our custom roles in QML.

We also define the sendMessage() function that we want to call from QML, hence the Q_INVOKABLE macro.

Let’s take a look at the .cpp file:

This is very similar to sqlcontactmodel.cpp, with the exception that we are now operating on the Conversations table. We also define conversationsTableName as a static const variable, as we use it in a couple of places throughout the file.

As with SqlContactModel, the first thing that we do in the constructor is create the table. We tell QSqlTableModel the name of the table we’ll be using via the setTable() function. To ensure that the latest messages in the conversation are shown first, we sort the query results by the timestamp field in descending order. This goes hand in hand with setting ListView’s verticalLayoutDirection property to ListView.BottomToTop (which we covered in chapter 3).

In setRecipient(), we set a filter over the results returned from the database.

The data() function falls back to QSqlTableModel’s implementation if the role is not a custom user role. If the role is a user role, we can subtract Qt::UserRole from it to get the index of that field and then use that to find the value that we need to return.

In roleNames(), we return a mapping of our custom role values to role names. This enables us to use these roles in QML. It can be useful to declare an enum to hold all of the role values, but since we don’t refer to any specific value in code outside of this function, we don’t bother.

The sendMessage() function uses the given recipient and a message to insert a new record into the database. Due to our usage of QSqlTableModel::OnManualSubmit, we must manually call submitAll().

Connecting to the Database and Registering Types With QML#

Now that we’ve established the model classes, let’s take a look at main.cpp:

connectToDatabase() creates the connection to the SQLite database, creating the actual file if it doesn’t already exist.

Within main(), we call qmlRegisterType() to register our models as types within QML.

Using the Models in QML#

Now that we have the models available as QML types, there are some minor changes to be done to ContactPage.qml. To be able to use the types, we must first import them using the URI we set in main.cpp:

We then replace the dummy model with the proper one:

Within the delegate, we use a different syntax for accessing the model data:

In ConversationPage.qml, we add the same chattutorial import, and replace the dummy model:

Within the model, we set the recipient property to the name of the contact for which the page is being displayed.

The root delegate item changes from a Row to a Column, to accommodate the timestamp that we want to display below every message:


Now that we have a proper model, we can use its recipient role in the expression for the sentByMe property.

The Rectangle that was used for the avatar has been converted into an Image. The image has its own implicit size, so we don’t need to specify it explicitly. As before, we only show the avatar when the author isn’t the user, except this time we set the source of the image to an empty URL instead of using the visible property.

We want each message background to be slightly wider (12 pixels each side) than its text. However, if it’s too long, we want to limit its width to the edge of the listview, hence the usage of Math.min(). When the message wasn’t sent by us, an avatar will always come before it, so we account for that by subtracting the width of the avatar and the row spacing.

For example, in the image above, the implicit width of the message text is the smaller value. However, in the image below, the message text is quite long, so the smaller value (the width of the view) is chosen, ensuring that the text stops at the opposite edge of the screen:


In order to display the timestamp for each message that we discussed earlier, we use a Label. The date and time are formatted with Qt.formatDateTime(), using a custom format.

The “send” button must now react to being clicked:

First, we call the invokable sendMessage() function of the model, which inserts a new row into the Conversations database table. Then, we clear the text field to make way for future input.


Chapter 5: Styling#

Styles in Qt Quick Controls are designed to work on any platform. In this chapter, we’ll do some minor visual tweaks to make sure our application looks good when run with the Basic , Material , and Universal styles.

So far, we’ve just been testing the application with the Basic style. If we run it with the Material Style , for example, we’ll immediately see some issues. Here is the Contacts page:


The header text is black on a dark blue background, which is very difficult to read. The same thing occurs with the Conversations page:


The solution is to tell the toolbar that it should use the “Dark” theme, so that this information is propagated to its children, allowing them to switch their text color to something lighter. The simplest way of doing so is to import the Material style directly and use the Material attached property:

import QtQuick.Controls.Material 2.12

// ...

header: ToolBar {
    Material.theme: Material.Dark

    // ...

However, this brings with it a hard dependency to the Material style; the Material style plugin must be deployed with the application, even if the target device doesn’t use it, otherwise the QML engine will fail to find the import.

Instead, it is better to rely on Qt Quick Controls’s built-in support for style-based file selectors . To do this, we must move the ToolBar out into its own file. We’ll call it ChatToolBar.qml. This will be the “default” version of the file, which means that it will be used when the Basic style (which is the style that is used when none is specified) is in use. Here’s the new file:

As we only use the ToolBar type within this file, we only need the Qt Quick Controls import. The code itself has not changed from how it was in ContactPage.qml, which is how it should be; for the default version of the file, nothing needs to be different.

Back in ContactPage.qml, we update the code to use the new type:

Now we need to add the Material version of the toolbar. File selectors expect variants of a file to be in appropriately named directories that exist alongside the default version of the file. This means that we need to add a folder named “+Material” in the same directory that ChatToolBar.qml is in: the root folder. The “+” is required by QFileSelector as a way of ensuring that the selection feature is not accidentally triggered.

Here’s +Material/ChatToolBar.qml:

We’ll make the same changes to ConversationPage.qml:

Now both pages look correct:

../_images/qtquickcontrols-chattutorial-chapter5-contacts-material.png ../_images/qtquickcontrols-chattutorial-chapter5-conversations-material.png

Let’s try out the Universal style:

../_images/qtquickcontrols-chattutorial-chapter5-contacts-universal.png ../_images/qtquickcontrols-chattutorial-chapter5-conversations-universal.png

No issues there. For a relatively simple application such as this one, there should be very few adjustments necessary when switching styles.

Now let’s try each style’s dark theme. The Basic style has no dark theme, as it would add a slight overhead to a style that is designed to be as performant as possible. We’ll test out the Material style first, so add an entry to qtquickcontrols2.conf that tells it to use its dark theme:


Once this is done, build and run the application. This is what you should see:

../_images/qtquickcontrols-chattutorial-chapter5-contacts-material-dark.png ../_images/qtquickcontrols-chattutorial-chapter5-conversations-material-dark.png

Both pages look fine. Now add an entry for the Universal style:


After building and running the application, you should see these results:

../_images/qtquickcontrols-chattutorial-chapter5-contacts-universal-dark.png ../_images/qtquickcontrols-chattutorial-chapter5-conversations-universal-dark.png


In this tutorial, we’ve taken you through the following steps of writing a basic application using Qt Quick Controls:

  • Creating a new project using Qt Creator.

  • Setting up a basic ApplicationWindow .

  • Defining headers and footers with Page.

  • Displaying content in a ListView.

  • Refactoring components into their own files.

  • Navigating between screens with StackView .

  • Using layouts to allow an application to resize gracefully.

  • Implementing both custom read-only and writable models that integrate an SQL database into the application.

  • Integrating C++ with QML via Q_PROPERTY, Q_INVOKABLE, and qmlRegisterType().

  • Testing and configuring multiple styles.