Book Image

Learn Qt 5

By : Nicholas Sherriff
Book Image

Learn Qt 5

By: Nicholas Sherriff

Overview of this book

Qt is a mature and powerful framework for delivering sophisticated applications across a multitude of platforms. It has a rich history in the Linux world, is widely used in embedded devices, and has made great strides in the Mobile arena over the past few years. However, in the Microsoft Windows and Apple Mac OS X worlds, the dominance of C#/.NET and Objective-C/Cocoa means that Qt is often overlooked. This book demonstrates the power and flexibility of the Qt framework for desktop application development and shows how you can write your application once and deploy it to multiple operating systems. Build a complete real-world line of business (LOB) solution from scratch, with distinct C++ library, QML user interface, and QtTest-driven unit-test projects. This is a suite of essential techniques that cover the core requirements for most LOB applications and will empower you to progress from a blank page to shipped application.
Table of Contents (11 chapters)

Installing Qt

Let’s start things off by visiting the Qt website at

The site layout changes fairly frequently, but what you are looking for is to download Qt Open Source for Desktop & Mobile:

  1. From the top-level menu, select Products and then IDE & Tools
  2. Click on Start for Free
  3. Select Desktop & Mobile Applications
  4. Click on Get your open source package
If you continue to use Qt beyond these personal projects, ensure that you read the licensing information available on the Qt website ( Upgrade to the commercial Qt license if the scope of your projects requires it or if you want access to the official Qt support and the benefits of a close strategic relationship with the Qt company.

The site will detect your operating system and suggest a recommended download:

On Windows, you will be recommended the online installer *.exe file, while on Linux you will be offered a *.run file, and a .dmg file if you are running Mac OS X. In all cases, download and launch the installer:

On Linux, once downloaded, you may need to first navigate to the *.run file and mark it as executable in order to be able to launch it. To do this, right-click on the file in the file manager and click on Properties. Click on the Permissions tab and tick the box that says Allow executing file as program.

After the initial welcome dialog, the first thing you are presented with is the option to sign up for or log in with a Qt account. Feel free to create one if you wish, but for now we’ll go ahead and Skip:

You are then asked to select which components you wish to install.

Your first decision is which version(s) of the Qt framework you want. You can have multiple versions installed side by side. Let's select the latest and greatest (Qt 5.10 at the time of writing) and leave all the older versions unchecked.

Next, expand the selected version and you will see a secondary list of options. All the options where the description reads “Qt 5.9.x Prebuilt Components for ...” are what is known as a Kit. A Kit is essentially a toolset enabling you to build your application with a specific compiler/linker and run it on a particular target architecture. Each kit comes with Qt framework binaries compiled specifically for that particular toolset as well as necessary supporting files. Note that kits do not come with the referenced compiler; you will need to install those ahead of time. One exception to this on Windows is MinGW (which includes GCC for Windows), which you can optionally install via the Tools component list at the bottom.

On Windows, that is exactly what we’ll do, so we select the MinGW 5.3.0 32 bit kit and also the MinGW 5.3.0 development environment from the Tools section. On my (64-bit) machine, I already have Microsoft Visual Studio 2017 installed, so we will also select the MSVC 2017 64-bit kit to help demonstrate some techniques later in the book. On Linux, we select GCC 64-bit, while on Mac OS, we select macOS 64-bit (which uses the Clang compiler). Note that on Mac OS, you must have XCode installed, and it's a good idea to launch XCode at least once to give it an opportunity to complete its initialization and configuration.

Feel free to press pause, go and install whatever other IDEs or compilers you want to use, and then come back and pick the kits to match. It doesn’t matter too much which you go for—the techniques explained throughout the book are applicable regardless of the kit, you may just get slightly different results. Note that the available kits you are presented with will differ depending on your operating system and chipset; for example, if you are on a 32 bit machine, you won’t be offered any 64 bit kits.

Below the kits are some optional Qt APIs (such as Qt Charts), which we won’t need for the topics covered in this book, but feel free to add them in if you want to explore their functionality. Note that they may have different licensing agreements from the core Qt framework.

Regardless of kits and APIs, you will note in the Tools section that Qt Creator is installed by default and that is the IDE we will be using throughout this book:

Once you are finished making your selections, click on Next and Update to kick off the installation.

It's generally a good idea to leave the installation location as the default for consistency across machines, but feel free to install it wherever you want.

Maintaining your installation

Once installed, you can update, add, and remove components (or even the entire Qt installation) via the Maintenance Tool application that is located in the directory you installed Qt to.

Launching this tool provides pretty much the same experience as when we first installed Qt. The Add or remove components option is the one you want to add in items you may have previously not needed, including kits and even entirely new releases of the framework. Unless you actively uncheck them, components already installed on your system will not be affected.

Qt Creator

While a detailed overview of Qt Creator is beyond the scope of this book (the Qt Creator manual is accessible via the Help mode as described here), it’s worth having a quick whistle stop tour before we get stuck to our first project, so launch the freshly installed application and we’ll take a look:

At the upper left-hand side (1) are the different areas or modes of the application:

  • Welcome mode is the default when Qt Creator is launched and is the jumping off point to create or open projects. There is an extensive set of examples that help showcase the various capabilities of the framework as well as a selection of tutorial videos.
  • Edit mode is where you will be spending the vast majority of your time and is used for editing all the various text-based files.
  • Design is accessible only when you have a UI file open and is a WYSIWYG editor for views. Although useful for UX design and basic layout work, it can get frustrating quite quickly and we will do all of our QML work in Edit mode instead. Working this way promotes understanding of the QML (as you have to write it) and also has the advantage that the editor is not adding code that you don’t want.
  • Debug mode is used for debugging applications and is beyond the scope of this book.
  • Projects mode is where configuration for the project is managed, including the build settings. Changes made here will be reflected in the *.pro.user file.
  • Help mode takes you to the Qt Creator manual and Qt library reference.
Pressing F1 while the cursor is on a recognized Qt symbol will automatically open context sensitive help for that symbol.

Below that, we have the build/run tools (2):

  • Kit/Build lets you select your kit and set the build mode
  • Run builds and runs the application without debugging
  • Start Debugging builds and runs the application with a debugger (note that you must have a debugger installed and configured in your selected kit for this to work)
  • Build Project builds the application without running it

Along the bottom (3), we have a search box and then several output windows:

Issues displays any warnings or errors. For compiler errors relating to your code, double-clicking on the item will navigate you to the relevant source code.

  • Search Results lets you find occurrences of text within various scopes. Ctrl + F brings up a quick search, and from there selecting Advanced… also brings up the Search Results console.
  • Application Output is the console window; all output from application code like std:: cout and Qt’s equivalent qDebug() appears here, along with certain messages from the Qt framework.
  • Compile Output contains output from the build process, from qmake through to compilation and linking.
  • Debugger Console contains debugging information that we won’t be covering in this book.
  • General Messages contains other miscellaneous output, the most useful of which is from qmake parsing of *.pro files, which we will look at later.

The search box really is a hidden gem and saves you from clicking through endless files and folders trying to find what you are looking for. You can start typing the name of a file you are looking for in the box and a filtered list appears with all matching files. Simply click on the file you want, and it opens in the editor. Not only that, there are a large number of filters you can apply too. Click your cursor in the empty search box and it displays a list of available filters. The filter m, for example, searches for C++ methods. So, say you remember writing a method called SomeAmazingFunction() but can't remember where it is, just head over to the search box, start typing m Some, and it will appear in the filtered list.

In Edit mode, the layout changes slightly and some new panes appear. Initially, they will be empty, but once you have a project open, they will resemble the following:

Next to the navigation bar is the project explorer, which you can use to navigate the files and folders of your solution. The lower pane is a list of all of the documents you currently have open. The larger area to the right is the editor pane where you write your code and edit documents.

Double-clicking on a file in the project explorer will generally open it in the editor pane and add it to the open documents list. Clicking on a document in the open documents list will activate it in the editor pane, while clicking on the small x to the right of the filename closes it.

Panes can be changed to display different information, resized, split, closed, and possibly filtered or synchronized with the editor using the buttons in the headers. Experiment to get a feel for what they can do.

As you would expect with a modern IDE, the look and feel of the chrome and the text editor is very customizable. Select Tools > Options… to see what is available. I generally edit the following:

  • Environment > Interface > Theme > Flat
  • Text Editor > Fonts & Colors > Color Scheme > My own scheme
  • Text Editor > Completion > Surround text selection with brackets > Off
  • Text Editor > Completion > Surround text selection with quotes > Off
  • C++ > Code Style > Current Settings > Copy… then Edit…
  • Edit Code Style > Pointers and References > Bind to Type name > On (other options Off)

Play around and get things how you like them.

Scratchpad project

To demonstrate how minimal a Qt project can be and to give us a programming sandpit to play around in, we’ll create a simple scratchpad project. For this project, we won’t even use the IDE to do it for us, so you can really see how projects are built up.

First, we need to create a root folder to store all of our Qt projects. On Windows, I use c:\projects\qt, while I use ~/projects/qt on Linux and Mac OS. Create this folder wherever works for you.

Note that file syncing tools (OneDrive, DropBox, and so on) can sometimes cause problems with project folders, so keep your project files in a regular unsynchronized folder and use version control with a remote repository for backups and sharing.

For the remainder of the book, I will loosely refer to this folder as <Qt Projects> or similar. We will also tend toward using the Unix style / separator for file paths, rather than Windows style back slash \. So, for readers using Windows, <Qt Projects>/scratchpad/amazing/code is equivalent to c:\projects\qt\scratchpad\amazing\code. Qt tends to favor this convention too.

Equally, the majority of screenshots in the remainder of the book will be from Windows, so Linux/Mac users should interpret any references to c:\projects\qt as ~/projects/qt.

In our Qt projects folder, create a new folder scratchpad and navigate into it. Create a new plain text file called, remembering to remove any .txt extension the operating system may want to add for you.

Next, simply double-click on the file and it will open in Qt Creator:

Here, Qt Creator is asking us how we want our project to be configured, namely, which kits we want to use when building and running our code. Pick one or more available kits and click on Configure Project. You can easily add and remove kits later, so don’t worry about which ones you select.

If you switch back to the filesystem, you will see that Qt Creator has created a new file for us called This is just an XML file containing configuration information. If you delete this file and open the .pro file again, you will be prompted to configure the project again. As its name suggests, the configuration settings are relevant to the local user, so often if you load a project created by someone else, you will need to go through the configure project step then too.

With the project successfully configured, you will see the project has been opened, even with a completely empty .pro file. That's about as minimal as a project can get!

Back in the filesystem, create the following plain text files:

  • main.cpp
  • main.qml
  • qml.qrc

I will go through each of these files, explain their purpose, and add their content soon. In a real-world project, we would of course use the IDE to create the files for us. Indeed, that’s exactly what we’ll do when we create our main solution files. However, the purpose of doing it this way is to show you that when you boil it down, a project is just a bunch of text files. Never be afraid to create and edit files manually. A lot of modern IDEs can confuse and overcomplicate with menu after menu and never-ending option windows. Qt Creator may miss some of the advanced bells and whistles of other IDEs but is refreshingly lean and straightforward.

With those files created, double-click on the file in the Projects pane and we’ll start editing our new project.


Our project (.pro) files are parsed by a utility called qmake, which in turn generates Makefiles that drive the building of the application. We define the type of project output we want, what source files are included as well as the dependencies and much more. Much of this is achieved by simply setting variables as we will do in our project file now.

Add the following to


QT += qml quick

CONFIG += c++14
SOURCES += main.cpp
RESOURCES += qml.qrc

Let’s run through each of these lines in turn:


TEMPLATE tells qmake what type of project this is. In our case, it’s an executable application that is represented by app. Other values we are interested in are lib for building library binaries and subdirs for multi project solutions. Note that we set a variable with the = operator:

QT += qml quick

Qt is a modular framework that allows you to pull in only the parts you need. The QT flag specifies the Qt modules we want to use. The core and gui modules are included by default. Note that we append additional values to a variable that expects a list with +=:

CONFIG += c++14

CONFIG allows you to add project configuration and compiler options. In this case, we are specifying that we want to make use of C++14 features. Note that these language feature flags will have no effect if the compiler you are using does not support them:

SOURCES += main.cpp

SOURCES is a list of all the *.cpp source files we want to include in the project. Here, we add our empty main.cpp file, where we will implement our main() function. We don’t have any yet, but when we do, our header files will be specified with a HEADERS variable:

RESOURCES += qml.qrc 

RESOURCES is a list of all the resource collection files (*.qrc) included in the project. Resource collection files are used for managing application resources such as images and fonts, but most crucially for us, our QML files.

With the project file updated, save the changes.

Whenever you save a change to your *.pro files, qmake will parse the file. If all is well, you will get a small green bar at the bottom-right of Qt Creator. A red bar indicates some kind of issue, usually a syntax error. Any output from the process will be written out to the General Messages window to help you diagnose and fix the problem. White space is ignored, so don’t worry about matching up the blank lines exactly.

To get qmake to take a fresh look at your project and generate new Makefiles, right-click on your project in the Projects pane and select Run qmake. It may be slightly tedious, but it’s a good habit to manually run qmake in this way on each of your projects before building and running your application. I’ve found that certain types of code changes can “slip under the radar” and leave you scratching your head when you run your application and they don’t seem to have had any effect. If you ever see your application ignoring the changes you’ve just made, run qmake on each of your projects and try again. The same applies if you get spurious linker errors.

You will see that our other files have now magically appeared in the Projects pane:

Double-click on main.cpp to edit it, and we’ll write our first bit of code:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine;
return app.exec(); }

All we are doing here is instantiating a Qt GUI application object and asking it to load our main.qml file. It’s very short and simple because the Qt framework does all the complex low-level work for us. We don’t have to worry about platform detection or managing window handles or OpenGL.

Possibly one of the most useful things to learn is that placing the cursor in one of the Qt objects and pressing F1 will open the help for that type. The same is true for methods and properties on Qt objects. Poke around in the help files to see what QGuiApplication and QQmlApplicationEngine are all about.

To edit the next file in our project—qml.qrc—you need to right-click and select the editor you want to open it with. The default is Resource Editor:

I am personally not a fan of this editor. I don’t feel it makes editing any easier than just writing plain text and isn’t particularly intuitive. Close this and instead choose Open with > Plain Text Editor.

Add the following content:

    <qresource prefix="/">

Back in main.cpp, we asked Qt to load the qrc:/main.qml file. This essentially breaks down as “look for the file in a qrc file with a prefix of / and a name of main.qml. Now here in our qrc file, we have created a qresource element with a prefix property of /. Inside this element, we have a collection of resources (albeit only one of them) that has the name main.qml. Think of qrc files as a portable filesystem. Note that the resource files are located relative to the .qrc file that references them. In this case, our main.qml file is in the same folder as our qml.qrc file. If it was in a subfolder called views, for example, then the line in qml.qrc would read this way:


Similarly, the string in main.cpp would be qrc:/views/main.qml.

Once those changes are saved, you will see our empty main.qml file appear as a child of the qml.qrc file in the Projects pane. Double-click on that file to edit it, and we will finish off our project:

import QtQuick 2.9
import QtQuick.Window 2.3

Window {
visible: true
width: 1024
height: 768
title: qsTr("Scratchpad")
color: "#ffffff"

Text {
id: message
anchors.centerIn: parent
font.pixelSize: 44
text: qsTr("Hello Qt Scratchpad!")
color: "#008000"

We will cover QML in detail in Chapter 2, Project Structure, but in brief, this file represents the screen or view presented to the user when the application launches.

The import lines are similar to #include statements in C++, though rather than including a single header file, they import a whole module. In this case, we want the base QtQuick module to give us access to all the core QML types and also the QtQuick window module to give us access to the Window component. Modules are versioned and generally, you will want to use the latest version for the release of Qt you are using. The current version numbers can be found in the Qt documentation. Note that although you get code completion when entering the version numbers, the options presented sometimes don’t reflect the latest available versions.

As its name suggests, the Window element gives us a top-level window, inside which all of our other content will be rendered. We give it a size of 1024 x 765 pixels, a title of “scratchpad” and a background color of white represented as a hex RGB value.

Within that component (QML is a hierarchical markup language), we add a welcome message with the Text component. We center the text in the screen and set its font size and color, but other than that, we’re not concerned with fancy formatting or anything at this stage, so that’s as complicated as we’ll make it. Again, we’ll cover this in more detail later, so don’t worry if it seems a bit alien.

That’s it. To build and run our amazing new application, first select the Kit and Build configuration you want using the monitor icon at the bottom-left:

Next, right-click on the project name in the Projects pane and select Run qmake. When that has completed, Run the application using the green play icon: