Application Development with Qt Creator - Third Edition

5 (1 reviews total)
By Lee Zhi Eng , Ray Rischpater
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with Qt Creator

About this book

Qt is a powerful development framework that serves as a complete toolset for building cross-platform applications, helping you reduce development time and improve productivity. Completely revised and updated to cover C++17 and the latest developments in Qt 5.12, this comprehensive guide is the third edition of Application Development with Qt Creator.

You'll start by designing a user interface using Qt Designer and learn how to instantiate custom messages, forms, and dialogues. You'll then understand Qt's support for multithreading, a key tool for making applications responsive, and the use of Qt's Model-View-Controller (MVC) to display data and content. As you advance, you'll learn to draw images on screen using Graphics View Framework and create custom widgets that interoperate with Qt Widgets. This Qt programming book takes you through Qt Creator's latest features, such as Qt Quick Controls 2, enhanced CMake support, a new graphical editor for SCXML, and a model editor. You'll even work with multimedia and sensors using Qt Quick, and finally develop applications for mobile, IoT, and embedded devices using Qt Creator.

By the end of this Qt book, you'll be able to create your own cross-platform applications from scratch using Qt Creator and the C++ programming language.

Publication date:
January 2020
Publisher
Packt
Pages
426
ISBN
9781789951752

 

Getting Started with Qt Creator

Qt Creator is an integrated software development environment that supports both traditional C++ application development and development using the Qt project's libraries (collectively called Qt and pronounced as cute).

Qt is available under a commercial license as well as under GPL v3 and LGPL v2. Its development dates all the way back to 1991. For the first 10 years of its life, it was a cross-platform toolkit for Windows and X11; by 2001, support for macOS X had been added.

In this chapter, we will take a look at everything you need to get started, as follows:

  • Where to download Qt Creator for Linux, macOS X, and Windows
  • New features in the latest version of Qt
  • How to ensure that your basic configuration is running
  • A quick look at a simple Qt Widgets application as well as a Qt Quick application
 

Technical requirements

 

Downloading Qt and Qt Creator

Qt, the cross-platform toolkit behind Qt Creator, has had a long and illustrious history. Presently a project of The Qt Company, it has its own URL: http://www.qt.io. It also has both commercial and non-commercial licenses. To get started with the non-commercial version for free, go to http://www.qt.io/download-qt-installer. You should see something similar to the following screenshot:

One of the most popular platforms for application development with Qt is Linux. On many Linux variants—notably Ubuntu, my personal favorite – you can get Qt Creator using the package manager. On my Ubuntu box, Qt Creator is just a sudo apt-get install qtcreator command away. You'll get a version of Qt that matches your flavor of Linux, although it might not be the latest and greatest build from The Qt Company. If you need to install the latest official version of Qt, it's recommended to download it from the preceding link.

Some downloads include the C++ compiler and the linker that you need. By following the link and downloading Qt, you should now have Qt, Qt Creator, and the MinGW toolkit for developing software on Windows. If you're developing on Linux or Mac, the process will be similar, although it won't include MinGW in your development. On Windows, there's a variant that includes the MinGW toolchain, so you have everything you need to build applications.

However, you can also download Qt Creator for Windows, which uses the Microsoft Visual Studio compiler. So, if you prefer using Visual Studio for your compilation and Qt Creator as your IDE, this is also an option. On macOS X, you'll need to have Xcode and the command-line development tools installed first; you can download Xcode from the macOS X App Store and then use Xcode to download the command-line development tools.

Once the installer downloads, run it in the usual way and it'll launch an installation wizard for your platform. Depending on whether you're running the online installer or the offline installer, installation for the latter should typically take anywhere from 3 to 4 minutes; however, it may take several hours if you're running the online installer. This is because when you run the installation process, the online installer downloads every single tool and library file from the Qt server uncompressed. On the other hand, the offline installer contains all the tools and libraries in a heavily compressed format packed within the installer itself, which is why the installation process is relatively quicker and simpler, but has a larger-sized installer compared to the online installer.

Other than that, you'll want to have plenty of disk space. Qt Creator doesn't consume that much disk space, but software development does; you'll need at least 500 MB of empty space for the tools and libraries, and you'll need to budget a few free gigabytes on your main drive for your source code, intermediate object files, debugging symbols, and, of course, your compiled application. (It is especially important to plan for this if you're running Qt Creator on a virtual machine; make sure that the virtual hard drive for your virtual machine image has plenty of disk space.)

You should also ensure that your development box has plenty of RAM; the more, the better. Qt Creator runs happily on 2 GB of RAM, but the compiler and linker used by Qt Creator can run a lot faster if they have more RAM available.

 

New features in Qt

Qt developers are constantly adding new features to Qt while fixing critical bugs that affect its users. This means that we can expect new features in every update of Qt, especially a major release. At the time of writing this chapter, the latest stable version of Qt is 5.12.3, which means it's the third minor update for its major version, 5.12.

Some of the important changes to Qt since the second edition of this book are as follows:

  • Qt WebView (WebKit) has been deprecated and replaced by Qt WebEngine (Chromium).
  • MinGW 64-bit compiler is now included in Qt's Windows installer.
  • Many features have been added to the mobile platforms, including support for in-app purchasing.
  • Qt Script, Qt Quick Control 1, and Qt Canvas 3D have been deprecated.
  • Added support for new platforms, such as tvOS and watchOS.
  • Previously commercial-only features such as Qt Charts, Qt Data Visualization, Qt Virtual Keyboard, Qt Purchasing, and Qt Quick 2D Renderer are now free.
  • Added support for embedded platforms.
  • Added Qt Automotive Suite.
  • Qt binding for Python has been added (using the PySide 2 module).
  • New signal and slot connection syntax – you can now directly connect a signal to a C++11 lambda function.
  • Added support for JSON format.
  • Added Qt 3D Studio.
  • Added SCXML and state machine tooling in Qt Creator.

...and there are many more besides!

To learn more about the new features and changes in the latest Qt release, please check out the official introduction for Qt 5 at https://doc.qt.io/qt-5/qt5-intro.html, or head over to the wiki page at https://wiki.qt.io/Main.
 

Finding your way around Qt Creator

The following screenshot shows what you will see when you launch Qt Creator for the first time. Let's take a closer look at each portion of the screen:

The main window, which currently shows the buttons for New Project and Open Project, is your workspace. The workspace also includes links to the Qt projects, examples, and tutorials, as well as Qt's developer documentation, such as its online community and blogs. Under normal conditions, this will be located where you'll see the source code for your application. Along the left-hand side of the screen are a series of icons that let you select various views in your application. They are as follows:

  • The Welcome mode, which shows basic information about Qt Creator
  • The Edit mode, which lets you edit the files that make up your application
  • The Design mode, which lets you use Qt Designer to design the user interface for your application
  • The Debug mode, which lets you debug your application while it's running, including doing things such as viewing the memory and variables, setting breakpoints, and stepping through the application
  • The Projects mode, which lets you adjust the build and link settings for your project
  • The Analyze mode, which lets you profile your application's runtime performance
  • The Help mode, which provides documentation on Qt Creator and the Qt framework

Let's create a new project using C++.

 

Your first application – Hello World

In Qt Creator, select New File or Project from the File menu. Qt Creator will present you with the New File or Project wizard, which lets you choose the kind of project you want to create, give it a name, and so on. To create your first application, perform the following steps:

  1. Select New File or Project if you haven't done so already.
  2. Qt Creator presents you with a dialog that has a dizzying array of project choices. Choose Application, then Qt Console Application, and then click on Choose....
  3. Qt Creator asks you for a name and a path to the directory where you want to store the files for the project. For the name, enter HelloWorldConsole and choose a path that makes sense to you (or accept the default). Then, click on Next.
  4. Qt Creator asks you for the build system you want to use for your project. Just keep the default option, qmake, if you don't have any specific requirements for this. Then, click on Next:
  1. Qt Creator can support various kits and libraries against which you can build an application. Select the desktop Qt Kit, which should have been installed by default. If you're running Qt on Windows, please make sure that you select the desktop Qt Kit with MinGW, as it is installed by default. Make sure that you have installed Microsoft Visual Studio beforehand if you pick the desktop Qt MSVC Kit. Then, click on Next.
  2. In the next step, Qt Creator prompts you about the version control system for your project. Qt Creator can use your installed version control clients to perform change tracking for your project. For now, skip this and leave Add to version control set to None. Then, click on Finish.

Qt Creator creates your project and switches to the Edit view. In the source code editor for the main.cpp file, enter the highlighted code:

#include <QCoreApplication> 
#include <iostream> 
 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 
    cout << "Hello world!"; 
 
    return a.exec(); 
} 
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

The QCoreApplication task handles the entire system startup for an application, and every Qt Console app needs to create one and call its exec method as part of your main method. It sets up Qt's event handler and provides a bunch of porting helpers to determine things such as your application directory, library paths, and other details.

For a console application, that's all you need; you can freely mix and match Qt classes with the C++ standard library and Standard Template Library (STL) although once you master Qt's foundation classes, many STL constructs might feel somewhat limiting.

Next, let's compile and run the application. There are several ways to do this:

  1. Click on the green run arrow underneath the Help view button on the left to run the application, as follows:
  1. Hit F5 to build and run your application in the debugger.
  2. Click on Start Debugging from the Debug menu, as follows:
  1. Click on the green run arrow with the bug over the arrow in order to debug the application on the left.
  2. Choose Run from the Build menu (or hit Ctrl + R).
If you only want to build the application, you can click on the hammer icon under the Run and Debug icons.

Once the application starts, you'll see the Hello world! message in a console view, as follows:

When you choose one of these options, Qt Creator invokes the compiler and the linker to build your application. If you choose the Debug option, Qt Creator switches to the Debug view (which we will discuss in detail in Chapter 2, Building Applications with Qt Creator) as it starts your application.

 

Hello World using the Qt Widgets library

One of Qt's strengths is its rich collection of GUI elements that you can use to create windowed applications. Making a GUI application is similar in principle to making a console application; instead of choosing Qt Console Application, select Qt Widgets Application from the New dialog presented when you choose New File or Project. Try it now:

  1. First, close the current file and project by clicking on Close All Projects and Editors from the File menu.
  2. Next, click on New File or Project again and click on Qt Widgets Application from the first step of the wizard.
  3. Walk through the wizard again, naming your project HelloWorldGui.
  1. Then, select the default kit. The New project wizard will prompt you for the name of the class implementing your main window. Leave the QMainWindow subclass as is and the name as MainWindow. Skip the build system and version control dialog portions of the wizard.

Qt Creator creates a default subclass of the class that provides the platform's basic window in the mainwindow.h and mainwindow.cpp files and creates a form that will contain the widgets for your application's window.

The following screenshot shows a default form as you're editing it in Qt Designer. If you run the application at this point, you'll see an empty window. Instead, double-click on the Forms folder in the project tree (the second pane) of Qt Creator and then double-click on the mainwindow.ui file. Qt Creator switches to the Design view, and you'll see something similar to the following screenshot:

As you can see from the preceding screenshot, on the left-hand side is a list of the layouts that you can choose to organize widgets. These include spacers, views, containers, buttons, and other widgets; other than that, there are a variety of edit and layout options as well. In the middle of the window is the preview of the layout of your application's main window. Further to the right are panes that show the hierarchy of objects in your main window and the properties of any item that you have clicked on in the main window.

Placing widgets in Qt Designer

While we will explore Qt Designer more in Chapter 3, Designing Your Application with Qt Designer, you can get a feel for using it by building a simple UI. Begin by ensuring that you're in the Designer mode, then proceed as follows:

  1. Where it says Type Here, right-click and choose Remove menu bar.
  2. Drag a label (under Display Widgets in the left-hand side pane) and drop it in the window preview in the center pane.
  3. Double-click on the label that appears and type Hello world!.
  1. Grab a corner of the label and resize it so that the entire text is shown. You can also move it around in the window.
  2. Note that when you click on the label, the Property field in the lower-right pane is updated to show the properties of your new label.
  3. Drag a button (under Buttons in the left-hand side pane) and drop it in the window preview in the center pane.
  4. Double-click on the button and change its text to Exit.
  5. With the new button selected, change the objectName field in the Property browser to exitButton. You must follow the name described here so that the code generated when adding the slot function will be identical to the one shown in the next sample code snippet.
  6. Right-click on the button and select Go to slot.... A window appears with a list of slots (for now, you can think of a slot as something that is triggered on an action; we will discuss them more in Chapter 2, Building Applications with Qt Creator).
  7. Choose clicked() from the list that appears.
  8. Qt Creator returns to the Edit view for your mainwindow.cpp file. Change it to read as follows:
#include "mainwindow.h" 
#include "ui_mainwindow.h" 
#include <QApplication> 
MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    ui->setupUi(this); 
} 
 
MainWindow::~MainWindow() 
{ 
    delete ui; 
} 
 
voidMainWindow::on_exitButton_clicked() 
{ 
    QApplication::exit(); 
}

Before running your application, let's be sure that you understand the implementation of the MainWindow class. The constructor of the MainWindow class loads the description of the user interface for the main window and sets it up using the Qt Creator-generated Ui::MainWindow class. The destructor deletes the implementation of the code layout, and the on_exitButton_clicked method simply terminates the application by calling the exit static method implemented by the QApplication class.

Finally, we have to add the on_exitButton_clicked method declaration to mainwindow.h if it's not already added. Double-click on this file in the browser on the left and make sure that it reads as follows:

#ifndef MAINWINDOW_H 
#define MAINWINDOW_H 
 
#include <QMainWindow> 
 
namespaceUi { 
class MainWindow; 
} 
 
class MainWindow : public QMainWindow 
{ 
    Q_OBJECT 
     
public: 
    explicit MainWindow(QWidget *parent = 0); 
    ~MainWindow(); 
     
private slots: 
    void on_exitButton_clicked(); 
 
private: 
    Ui::MainWindow *ui; 
}; 
 
#endif // MAINWINDOW_H 

The key lines you need to add are highlighted in the previous listing.

We'll learn more about signals and slots in the next chapter; for now, it's enough for you to know that you're declaring a private function to be triggered when you click on the button.

Run the application. It should open a single window with the text Hello World!; clicking on the Exit button in the window (or on the close-box button in the upper-right corner) should close the application:

At this point, if you think you want to learn more about the Qt Widgets application, go ahead and try dragging other GUI items to the window, or explore the help documentation for the Qt Widgets application by switching to the Help view and clicking on Qt GUI from the list of help items.

 

Hello World using Qt Quick

Qt Quick is Qt's newer declarative framework for the user interface. With this, it's incredibly easy to create fluid applications with animated transitions and flowing user interfaces. Using Qt Quick, you can describe your user interface using QML, a JavaScript-like language that lets you declare user interface elements and how they relate; the Qt Quick runtime does most of the heavy lifting in the implementation of your application.

By now, you can guess how to create a Qt Quick project. Choose New File or Project from the File menu, click on Qt Quick Application - Empty, and then follow the wizard.

The wizard will ask you one additional question: the Qt Quick version to use. You should simply choose the latest version. Once you have walked through the wizard, you will end up with a simple application that actually displays Hello World in its own window. The code that it supplies is as follows:

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
}

If you know JavaScript, the syntax of this might look a little familiar, but it's still different. The first two lines are the import statements; they indicate which classes should be available to the QML runtime. At a minimum, all of your Qt Quick applications must import QtQuick, as this one does.

The QML follows. It declares a Window object of 640 × 480 pixels that determines the size of the application window. Inside the window, we can see two other properties besides the window size: visible and title. The visible property simply means whether you want to display the item by default, which in this case we do. The title property is just that: the Hello World text placed on your application's window header. Note that the value of the title property is actually the result of a function call to the qsTr function, which is Qt's built-in localization function. This looks at application resources to return the localized version of Hello World if it has been provided.

It's worth making a note of the qsTr function here; you can use this if you want your application to support multiple languages. The qsTr function is used to display the text in different languages based on the selected locale. You can ignore it if you don't plan on supporting multiple languages.

At this point, you can run the application in the usual way and you'll see a window with the text Hello World as the window title.

While the basic concepts and principles are similar, the Qt Quick designer is actually very different from the Qt Widgets designer due to the very nature of it – the Qt Quick designer is specially optimized for creating touch-based applications, while Qt Widgets is designed for creating desktop programs. Before we're able to demonstrate the Qt Quick designer, let's first create a QtQuick UI File by going to File, New File or Project, then select the QtQuick UI File under the Qt category. After that, use the MyGui component name and keep the MyGuiForm component form name. Then, press Next, followed by the Finish button.

Once you're done, Qt Creator will add MyGui.ui.qml and MyGui.qml to your project, and Qt Quick Designer will be launched automatically. Take a look at the following screenshot:

It shows a list of things you can add to the canvas, as well as the hierarchy of objects on the canvas, along with the properties of individual objects.

However, there are far fewer Qt Quick widgets that you can use compared to Qt Widgets. Other than that, the widgets in Qt Quick don't match the look and feel of the native platform to nearly the same extent. That's by design; Qt Widgets is for building conventional applications that match the native platform by using native controls with a native look and feel, while Qt Quick is used for creating device-independent applications with their own look and feel. For example, you'd probably write an enterprise data collection application using Qt Widgets, while you'd create a media center application using Qt Quick.

However, the manner of using the designer is the same in both cases. Let's add mouseArea to the main view and give it something to do:

  1. Select MyGuiForm.ui.qml from the list of files in Qt Creator and click on Design to see the Design view.
  2. In the Library pane, select QML Types and scroll down until you see Rectangle. Drag the rectangle to the center pane and drop it somewhere underneath the parent object called Item.
  3. With the rectangle selected in the window pane, select the red color for your rectangle under Colors.
  4. With the rectangle object selected, click on Layout in the Properties tab and mouse over the layouts until you see Fill to Parent. (This is the fifth icon under the Anchors and looks like a box with a border.) Click on it.
  5. Now, drag a MouseArea object out of the Library pane and drop it on your new rectangle.
  6. With the MouseArea object selected, repeat step 4 to make it fill the parent Rectangle object.
  7. Click on the small circle icon with an arrow located just beside the id property of the MouseArea. The icon will turn a red color once it's clicked. This will allow other QML scripts to access this object.
  8. Repeat step 7 for the rectangle object as well.
  9. Go back to the Edit view and modify main.qml to look similar to the following code snippet:
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")

MyGuiForm {
anchors.fill: parent
mouseArea.onClicked: {
rectangle.color = "blue";
}
}
}

In newer versions of Qt, the QML script has been separated into two formats: .qml and .ui.qml. The first format (.qml) is for writing the logic and operations you want to perform when a GUI event has been triggered by the user. The second format (.ui.qml) is only for the cosmetic definition of your GUI – where to position the objects, the size and color of the objects, and so on.

You can see that all of the changes made for the MyGui.ui.qml file were done in the Design view; as for main.qml, we have to use the text editor to write the logic code demonstrated previously. You can make use of the MyGuiForm class directly in main.qml and tell it what to do when the MouseArea is being pressed by the user. You will need to set an ID of the MouseArea so that the onClicked handler knows which object will be triggering the event (in this case, it's using the default name, mouseArea). The id property also lets other QMLs access the Rectangle by name (in this case, its name is simply the default name, rectangle), and the onClicked handler changes the rectangle item's color property to blue when the user presses on the MouseArea item.

Run the application. You'll see your red-colored rectangle fills the entire window, and clicking on the rectangle changes its color to blue.

 

Summary

Getting Qt Creator is easy; it's either just a web download away or, on most Linux platforms, an optional installation through the native package manager (although the versions delivered by a package manager might be slightly older than those you get from the Qt project's website).

Qt Creator organizes its source code for you in projects; when you first launch it, you can either create a default project or create a new project to contain the source code and resources for your application. Inside Qt Creator are all the options you need to compile and debug your application. In addition, it supports designer tools for developing both Qt Widgets and Qt Quick applications.

In the next chapter, we'll dig into the details of how to configure Qt Creator for compiling and editing your code, including how to add source files to your project, configure compiler and linker options, add dependencies to third-party libraries, and so on.

About the Authors

  • Lee Zhi Eng

    Lee Zhi Eng is a self-taught programmer who worked as an artist and programmer at several game studios before becoming a part-time lecturer for 2 years at a university, teaching game development subjects related to Unity and Unreal Engine.

    He has not only taken part in various projects related to games, interactive apps, and virtual reality but has also participated in multiple projects that are more oriented toward software and system development. When he is not writing code, he enjoys traveling, photography, and exploring new technologies.

    Browse publications by this author
  • Ray Rischpater

    Ray Rischpater is an engineer with over 20 years of experience in writing about and developing for mobile computing platforms. He holds a bachelor's degree in mathematics from the University of California and is a member of the IEEE, ACM, and ARRL. He has participated in the development of internet technologies and custom applications.

    Currently, he's employed as a technical program manager at Google. In his free time, he enjoys hiking and photography with his family and friends. He provides public service through amateur radio at the licensed station KF6GPE and also irregularly blogs. He has authored this book's previous editions as well as several other books.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Fast and effective purchase. I had the book within 3 minutes.

Recommended For You

Application Development with Qt Creator - Third Edition
Unlock this book and the full library for FREE
Start free trial