Home Programming Hands-On GUI Programming with C++ and Qt5

Hands-On GUI Programming with C++ and Qt5

By Lee Zhi Eng
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to Qt
About this book
Qt 5, the latest version of Qt, enables you to develop applications with complex user interfaces for multiple targets. It provides you with faster and smarter ways to create modern UIs and applications for multiple platforms. This book will teach you to design and build graphical user interfaces that are functional, appealing, and user-friendly. In the initial part of the book, you will learn what Qt 5 is and what you can do with it. You will explore the Qt Designer, discover the different types of widgets generally used in Qt 5, and then connect your application to the database to perform dynamic operations. Next, you will be introduced to Qt 5 chart which allows you to easily render different types of graphs and charts and incorporate List View Widgets in your application. You will also work with various Qt modules, like QtLocation, QtWebEngine, and the networking module through the course of the book. Finally, we will focus on cross-platform development with QT 5 that enables you to code once and run it everywhere, including mobile platforms. By the end of this book, you will have successfully learned about high-end GUI applications and will be capable of building many more powerful, cross-platform applications.
Publication date:
April 2018
Publisher
Packt
Pages
404
ISBN
9781788397827

 

Introduction to Qt

Qt (pronounced cute) has been used by software engineers and developers for more than two decades to create cross-platform applications since its first release. After several changes of ownership and numerous major code overhauls, Qt has become even more feature rich and supports even more platforms than it used to. Qt not only excels in desktop application development, but is also excellent for both mobile and embedded systems development.

In this chapter, we will cover the following topics :

  • What is Qt?
  • Why use Qt?
  • Using tools in Qt
  • Downloading and installing Qt
  • Setting up a working environment
  • Running our first Hello World Qt program

Throughout this chapter, we will learn more about the history of Qt. Then, we'll proceed to build our first example program using the latest version of Qt, which is Qt version 5. For the convenience of our readers, we will simply refer to it as Qt throughout the book.

 

What is Qt?

Currently, the latest version of Qt (as this book is being written) is version 5.10. This version incorporated a lot of new features as well as thousands of bug fixes, which makes Qt a really powerful and stable development kit for software developers and system engineers alike. Qt has a huge package of SDK (software development kit) that contains a wide range of tools and libraries for helping developers get their job done without worrying too much about technical issues related to a specific platform. Qt handles all the messy integration and compatibility issues for you behind the curtain so you don't have to deal with them. This will not only improve efficiency but also reduces development costs, especially when you're trying to develop cross-platform applications that cater to a wider range of users.

There are two types of license for Qt:

  • The first type is the Open Source License, which is free of charge, but only if your project/product fits their terms and conditions. For example, if you made any changes to the Qt's source code, it is an obligation for you to submit back those changes to Qt developers. Failure to do so could result in serious legal issues, and therefore, you might want to pick the second option instead.
  • The second type of license is the Commercial License, which gives you full rights to proprietary Qt source code modifications and keeps your application private. But of course, these privileges come with a set of fees.

If you're just starting to learn Qt, don't get pushed back by these terms, as you're certainly not going to modify the source code of Qt libraries or recompile it from source anyway, at least not now.

For more information regarding Qt's licensing, please visit https://www.qt.io/licensing-comparison.

Why use Qt?

It's not hard to see why Qt stands a chance of winning against all other existing SDKs out there in the market; first of all, cross-platform compatibility. You can hardly find any other development kits that support so many platforms without writing different sets of code for each platform. By eliminating these extra steps, programmers can just focus on developing their applications without the need to worry about the implementation of each and every platform-specific feature. Furthermore, your code will look clean without all the #ifdef macros and having to load different dependencies for different platforms.

Qt generally uses C++, which is a compiled language that generates small and efficient code. It is also well documented and follows a very consistent set of naming conventions, which reduces the learning curve for the developer.

Do be aware that Qt does include a small amount of features that only work on specific platforms. However, these are minimal and often for special use cases, such as Qt Sensors, which only work on mobile platforms; Qt Web Engine, which only works on desktops; Qt NFC, only for Android and Linux; and so on. Those are some very specific functionalities that only exist on certain platforms that support them. Other than that, common features are usually supported on all platforms.

Discovering tools in Qt

Qt comes with a set of tools that make programmers' lives easier. One of the tools is Qt Creator (seen in the following screenshot), which is an IDE (integrated development environment) that consists of a code editor and a GUI (graphical user interface) designer that works hand-in-hand with other Qt tools, such as the compiler, debugger, and so on. The most attractive tool among all is, of course, the GUI designer, which comes with two different types of editors: one for widget-based applications, called Qt Designer, and another for Qt Quick Application, called Qt Quick Designer. Both tools can be accessed directly in Qt Creator when you open up a relevant file format. Qt Creator also includes a built-in documentation viewer called Qt Assistant. It is really handy since you can look for the explanation about a certain Qt class or function by simply hovering the mouse cursor over the class name in your source code, and pressing the F1 key. Qt Assistant will then be opened and show you the documentation related to the Qt class or function:

Qt Designer

Qt Designer is normally used by developers to design GUIs for desktop applications, while Qt Quick Designer is usually used for mobile and embedded platforms. With that being said, both formats run just fine on both desktop and mobile formats, the only difference is the look and feel, and the types of languages used.

The GUI file saved by Qt Designer carries the .ui extension, which is saved in XML format. The file stores the attributes of each and every widget placed by the GUI designer, such as position, size, margin, tooltip, layout direction, and so on. It also saves the signal-and-slot event names within itself for easily connecting with the code in the later stages. This format does not support coding and only works for Qt C++ projects, namely widget-based application projects.

Qt Quick Designer

On the other hand, Qt Quick Designer saves GUI files in both .ui.qml and .qml formats. Qt Quick is a very different type of GUI system in terms of technological concept and development approach, which we will cover in Chapter 14, Qt Quick and QML. Instead of XML format, Qt Quick Designer saves its data in a declarative language similar to JavaScript called QML. QML not only allows the designer to customize their GUI in a CSS-like (Cascading Style Sheets) fashion, it also allows the programmer to write functional JavaScript within the QML file. As we mentioned earlier, .ui.qml is the file format used for visual decoration only while .qml contains application logic.

If you're doing a simple program using Qt Quick, you don't have to touch any C++ coding at all. That's especially welcoming for web developers because they can immediately pick up Qt Quick and develop their own application without a steep learning curve; everything is just so familiar to them. For much more complex software, you can even link C++ functions from QML, and vice versa. Again, if you're interested in learning more about Qt Quick and QML, please head over to Chapter 14, QtQuick and QML.

Since Qt Creator is also written in Qt libraries itself, it is also totally cross-platform. Hence, you can use the same set of tools across different development environments and develop a unified workflow for your team, resulting in better efficiency and cost-effectiveness.

Other than that, Qt comes with many different modules and plugins, which cover a wide range of functionality you need for your projects. There is often no need for you to look for other external libraries or dependencies and try and implement them yourself. The abstraction layer of Qt makes the backend implementation invisible to the users and results in a unified coding style and syntax. If you try to put together a bunch of external dependencies yourself, what you'll find is each library has its own distinctive coding style. It's quite a mess when mixing up all the different coding styles in the same project, unless you make your own abstraction layer, which is a very time-consuming task. Since Qt already includes most, if not all the modules that you need to create feature-rich applications, there is no need for you to implement your own.

For more information regarding the modules that come with Qt, please visit: http://doc.qt.io/qt-5/qtmodules.html.

That being said, there are also many third libraries out there that extend Qt for features that Qt itself does not support, such as libraries that focus on game development or any other features that are designed for the specific user group.

 

Downloading and installing Qt

Without wasting any time, let's begin with our installation! To get the free installer for Open Source Qt, first go to their website at https://www.qt.io. There, look for the button that says Download Qt (the website might look different if they have updated it). Do note that you might be downloading the free trial version for the Commercial Qt, which you cannot use after 30 days. Make sure that you are downloading the open source version of Qt instead. Also, you may want to pick the right installer for your platform, since there are many different installers of Qt for different operating systemsWindows, macOS, and Linux.

You might wonder why the installer is so small in size—it is only around 19 MB. This is because the unified online installer doesn't actually contain any of the Qt packages, but is rather a downloader client which helps you to download all the relevant files and install them to your computer once the download has completed. Once you have downloaded the online installer, double-click on it and you will be presented with an interface like this (the following example is running on a Windows system):

Click the Next button, and a DRM (Digital Rights Management) page will appear and ask you to log in with your Qt account. If you don't have one, you can also create your account on the same page:

Once you have logged in, you will see a message that says No valid commercial license available in your Qt Account for this host platform. Don't worry about that, just click the Next button to proceed.

Next, you will be asked to specify the installation path. The default path is usually just fine, but you can change it to any other path as you please. Also, you can either leave the Associate this common file types with Qt Creator option checked, or uncheck it manually if otherwise.

After that, you will be presented with a series of checkboxes with which you can select the version(s) of Qt you need to install to your computer. Typically, for new users, the default options are sufficient. If you don't need some of the options, such as support for Qt on Android, you can unselect them here to reduce the size of the download. You can always go back and add or remove Qt components later if needed, using the Maintenance Tool:

Next, you will be presented with the license agreement. Check the first option, which says I have read and agree to the terms contained in the license agreements, and click the Next button. Make sure you do read the terms and conditions stated in the license agreement!

Finally, the installer will ask you to enter a name to create a start menu shortcut for Qt. Once you're done, just click Next and then click Install. The download process will take a couple of minutes to a couple of hours, depending on your internet speed. Once all the files have been downloaded, the installer will automatically proceed to install the files to the installation path that you have just set in one of the previous steps.

Setting up the working environment

Since you have installed the latest version of Qt, let's fire up Qt Creator and start messing around by creating our first project! You should be able to find Qt Creator's shortcut icon either on your desktop or somewhere within your start menu.

Let's look at the steps to set up our environment:

  1. When you first start Qt Creator, you should see the following interface:
  1. Before you start creating your first project, there are several settings that you might want to tweak. Go to the top menu and select Tools | Options. A window that looks something like this will pop up on the screen:
  1. There are quite a number of different categories available on the left of the window. Each category represents a set of options you can set to customize how Qt Creator will look and operate. You may not want to touch the settings at all, but it's good to learn about them first. One of the first settings you might want to change is the Language option, which is available in the Environment category. Qt Creator provides us with an option to switch between different languages. Although it doesn't support all languages, most of the popular ones are available, such as English, French, German, Japanese, Chinese, Russian, and so on. Once you have selected your desired language, click Apply and restart Qt Creator. You must restart Qt Creator in order to see the changes.
  1. The next setting you probably need is the setting for indentation. By default, Qt uses space indentation, in which four spaces will be added to your script whenever you press the Tab key on your keyboard. Some people, like me, prefer tab indentation instead. You can change the indentation setting at C++ category.
Do note that if you are contributing to Qt project's source code, it's required that you use space indentation instead of tabs, which is the coding standard and style of the Qt project.
  1. Under the C++ category, you can find a Copy button located beside the Edit button, somewhere in the top right position. Click it and a new window will pop up.
  2. Insert a code style name of your own, as you can't edit the default built-in coding style. After you have created your own settings, click the Edit button. You can now see the actual Tabs And Indentation settings under the General tab:
  1. Do note that even though there is a Tabs And Indentation setting located at the Text Editor category, I believe it's an old setting that no longer has any effect in Qt Creator. There is also a note written on the UI that says Code indentation is configured in C++ and Qt Quick settings. A possible reason for this is that since Qt Creator now supports both C++ project and QML projects, Qt developers probably felt there was a need to separate the settings into two, so therefore the old setting is no longer valid. I'm pretty sure this section on Text Editor will be deprecated in the near future.
  1. Next, under the Build and Run category, you'll see a tab labeled Kits.
  1. This is where you can set the compile settings for each platform. As you can see from the next screenshot, my Qt does not support desktop build under MSVC (Microsoft Visual Studio Compiler) because I never installed Visual Studio on my computer. Instead, my Qt only supports desktop build under the MinGW (Minimal GNU for Windows) compiler. From this window, you can check and see if your Qt supports the platform and compiler you wanted for your project and make changes to it if necessary. But for now, we'll just leave it as it is. To learn more about what is a kit is and how to configure the build settings, please head over to Chapter 15, Cross-Platform Development:
  1. Finally, we can link our project to our version control server at the Version Control category.
  2. Version control allows you or your team to submit code changes to a centralized system so that each and every team member can obtain the same code without passing files around manually. When you're working in a big team, it's very difficult to manually keep track of the code changes, and even more so to merge the code done by different programmers. Version control systems are designed to solve these issues. Qt supports different types of version control systems, such as Git, SVN, Mercurial, Perforce, and so on. Although this is a very useful feature, especially if you're working in a team, we don't need to configure it for now:
 

Running our first Hello World Qt program

A Hello World program is a very simple program that does nothing more than display an output that says Hello, World! (or any other thing, not necessarily this) to show that the SDK is working properly. We don't need to write very long code to produce a Hello World program, we can do it using only the very minimum and the most basic code. In fact, we don't have to write any code in Qt, as it will generate the code when you first create your project!

Let's begin our project by following these steps:

  1. To create a new project in Qt, click the New Project button located at the welcome screen on your Qt Creator. Alternatively, you can also go to the top menu and select File | New File or Project.
  1. After that, you will be presented with a window which lets you select a template for your project or file. For this demonstration, we will pick Qt Widgets Application:
  1. After that, set your project name and project directory. You can also check the checkbox that says Use as default project location so that you can automatically get the same path when you create a new project in Qt next time.
  1. Next, Qt Creator will ask you to select one or more kits for your project. For this demonstration, we'll pick Desktop Qt with the MinGW compiler. Don't worry, as you are allowed to add or remove kits from your project later on during development:
  1. After that, you will be presented with a page that says Class Information. This is basically where you set the class name for your base window, but we're not going to change anything, so just click the Next button to proceed:
  1. Finally, it will ask you to link your project to your version control server. If you have not added any to Qt before, you can click the Configure button, which will bring you to the settings dialog that I showed you in the previous section of this chapter.
  2. For this demonstration, however, we'll keep the settings as <None> and press the Finish button. Qt Creator will then proceed to generate the necessary files for your project. After a second or two, Qt Creator will automatically switch to Edit mode and you should be able to see the files it created for you under the Project panel. You can open up any of the files by double-clicking on them in Qt Creator and they will be shown in the editor located on the right-hand side:
  1. Before we start compiling the project, let's open up the mainwindow.ui file under the Forms directory in your project panel. Don't worry too much about the user interface as we will cover it in the following chapter. What we need to do is to click and drag the Label icon under the Display Widgets category to the center of the window on the right, as shown in the following screenshot:
  1. After that, double-click on the Text Label widget and change the text to Hello World!. Once you're done, hit the Enter button on your keyboard:
  1. The final step is to press the Run button located at the bottom left corner that looks like this:
  1. We would normally build the program first and then run the program, but Qt Creator is smart enough to figure out that it needs to build it. However, it is still a good habit to build and run your application separately. After a few seconds of compiling, ... voila! You have created your first Hello World program using Qt!:
 

Summary

The existence of tools such as Qt Creator has made designing applications' user interfaces an easy and fun job for the developers. We no longer need to write a bunch of code just to create a single button, or change a bunch just to adjust the position of a text label, since Qt Designer will generate that code for us when we design our GUI. Qt has applied the WYSIWYG (what you see is what you get) philosophy into the working pipeline and it provides us with all the convenience and efficiency we need to get our jobs done.

In the next chapter, we will learn the ins and outs of Qt Creator and start designing our first GUI with Qt!

About the Author
  • 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
Latest Reviews (9 reviews total)
I have tried some other c++ with QTx before and this one is better from the standpoint of getting something accomplished than the others.
Ich habe eigentlich nach einem Buch zu QML gesucht und fand gleich 10 Bücher zu Themen die in anderen Verlagen zu kurz kommen, und das zum genialen Sonderpreis
Good explanation, easy to follow examples
Hands-On GUI Programming with C++ and Qt5
Unlock this book and the full library FREE for 7 days
Start now