Cross-Platform Development with Qt 6 and Modern C++ - Nibedit Dey - E-Book

Cross-Platform Development with Qt 6 and Modern C++ E-Book

Nibedit Dey

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Qt is a cross-platform application development framework widely used for developing applications that can run on a wide range of hardware platforms with little to no change in the underlying codebase. If you have basic knowledge of C++ and want to build desktop or mobile applications with a modern graphical user interface (GUI), Qt is the right choice for you. Cross-Platform Development with Qt 6 and Modern C++ helps you understand why Qt is one of the favorite GUI frameworks adopted by industries worldwide, covering the essentials of programming GUI apps across a multitude of platforms using the standard C++17 and Qt 6 features.
Starting with the fundamentals of the Qt framework, including the features offered by Qt Creator, this practical guide will show you how to create classic user interfaces using Qt Widgets and touch-friendly user interfaces using Qt Quick. As you advance, you'll explore the Qt Creator IDE for developing applications for multiple desktops as well as for embedded and mobile platforms. You will also learn advanced concepts about signals and slots. Finally, the book takes you through debugging and testing your app with Qt Creator IDE.
By the end of this book, you'll be able to build cross-platform applications with a modern GUI along with the speed and power of native apps.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 420

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Cross-Platform Development with Qt 6 and Modern C++

Design and build applications with modern graphical user interfaces without worrying about platform dependency

Nibedit Dey

BIRMINGHAM—MUMBAI

Cross-Platform Development with Qt 6 and Modern C++

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Aaron Lazar

Publishing Product Manager: Kushal Dave

Senior Editor: Storm Mann

Content Development Editor: Nithya Sadanandan

Technical Editor: Gaurav Gala

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Vinayak Purushotham

Production Designer: Aparna Bhagat

First published: May 2021

Production reference: 2230721

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80020-458-4

www.packt.com

To my mother for believing in my dreams and to my father for his sacrifices and supporting me through my ups and downs.

To my childhood English teacher Mr. Harendra Das, who laid the foundation and honed my English communication skills, and my Science teacher Mr. Jayanta Kumar Das, who introduced me to computer and used to say “You will write a book one day”!

– Nibedit Dey

Contributors

About the author

Nibedit Dey is a software engineer turned serial entrepreneur with over a decade of experience in building complex software-based products with amazing user interfaces. Before starting his entrepreneurial journey, he worked for Larsen & Toubro and Tektronix in different R&D roles. He holds a bachelor's degree in biomedical engineering and a master's degree in digital design and embedded systems. Specializing in Qt and embedded technologies, his current role involves end-to-end ownership of products right from architecture to delivery. Currently, he manages two technology-driven product start-ups named ibrum technologies and AIDIA Health. He is a tech-savvy developer who is passionate about embracing new technologies.

About the reviewers

Andrey Gavrilin is a senior software engineer in an international company that provides treasury management cloud solutions. He has an MSc degree in engineering (industrial automation) and has worked in different areas such as accounting and staffing, road data banks, web and Linux distribution development, and fintech. His interests include mathematics, electronics, embedded systems, full-stack web development, retro gaming, and retro programming.

Syed Aftab has a bachelor's degree in engineering with a focus on electronics and communications. He has around 16 years of experience in software product development. Syed is skilled in software development using C and C++ technologies on various platforms such as Unix, Linux, Windows, and embedded platforms.

Programming, sharing his programming experience, and mentoring juniors are his passions. You can get in touch with him at https://www.linkedin.com/in/syed-aftab-a06a1943/

Table of Contents

Preface

Section 1: The Basics

Chapter 1: Introduction to Qt 6

Technical requirements

Introducing Qt

Reasons for using Qt

Downloading and installing Qt

Downloading Qt

Installing Qt on Windows

Installing Qt on Linux

Installing Qt on macOS

Updating or removing Qt

Building Qt 6 from source

Installing Qt on Windows from source

Installing Qt on Linux from source

Installing Qt on macOS from source

Summary

Chapter 2: Introduction to Qt Creator

Technical requirements

Exploring the Qt Creator UI

Building a simple Qt application

Understanding advanced options

Managing kits

Qt Versions

Environment

Keyboard shortcuts

Text Editor

Splitting the coding window

Build options

Qt Assistant

Summary

Chapter 3: GUI Design Using Qt Widgets

Technical requirements

Introducing Qt widgets

Creating a UI with Qt Designer

Managing layouts

QVBoxLayout

QHBoxLayout

QGridLayout

Creating custom widgets

Creating Qt Style Sheets and custom themes

Using a QSS file

Exploring custom styles

Creating a custom style

Using a custom style

Using widgets, windows, and dialogs

Summary

Chapter 4: Qt Quick and QML

Technical requirements

Getting started with QML and Qt Quick

Understanding the QML type system

Understanding Qt Quick Controls

Styling Qt Quick Controls

Creating a simple Qt Quick application

Designing a UI with Qt Quick Designer

Positioners and layouts in QML

Manual positioning

Positioning with anchors

Positioners

Repeater

Qt Quick Layouts

Integrating QML with C++

Embedding C++ objects into QML with context properties

Registering a C++ class with the QML engine

Creating a QML extension plugin

Invoking QML methods inside a C++ class

Exposing a QML object pointer to C++

Integrating QML with JS

Importing a directory in QML

Handling mouse and touch events

MouseArea

MultiPointTouchArea

TapHandler

SwipeView

Summary

Section 2: Cross-Platform Development

Chapter 5: Cross-Platform Development

Technical requirements

Understanding cross-platform development

Understanding compilers

Adding custom compilers

Building with qmake

Qt Project (.pro) files

Understanding differences between .pro and .pri files

Understanding build settings

Platform-specific settings

Using Qt with Microsoft Visual Studio

Running a Qt application on Linux

Running a Qt application on macOS and iOS

Configuring Qt Creator for iOS

Configuring Qt Creator for Android

Other Qt-supported platforms

Porting from Qt 5 into Qt 6

Summary

Section 3: Advanced Programming, Debugging, and Deployment

Chapter 6: Signals and Slots

Technical requirements

Understanding Qt signals and slots

Understanding syntax

Declaring signals and slots

Connecting the signal to the slot

Connecting a single signal to multiple slots

Connecting multiple signals to a single slot

Connecting a signal to another signal

The working mechanism of Qt signals and slots

Qt's meta-object system

MOC generated code

Getting to know Qt's property system

Reading and writing properties with the Meta-Object System

Using signals and slots in Qt Designer

Understanding signals and the handler event system in QML

Adding a signal in QML

Connecting a signal to a function

Connecting a signal to a signal

Defining property attributes and understanding property binding

Integrating signals and slots between C++ and QML

Understanding events and the event loop

Managing events with an event filter

Drag and drop

Drag and drop in Qt Widgets

Drag and drop in QML

Summary

Chapter 7: Model View Programming

Technical requirements

Understanding the M/V architecture

Model

Delegate

Views in Qt Widgets

Creating a simple Qt Widgets application using the M/V pattern

Understanding Models and Views in QML

Views in Qt Quick

Models in Qt Quick

Using C++ Models with QML

Creating a simple M/V application with Qt Quick

Summary

Chapter 8: Graphics and Animations

Technical requirements

Understanding Qt's graphics framework

QPainter and 2D graphics

Understanding the paint system

Using the coordinate system

Drawing and filling

Drawing with QPainter

Introducing the Graphics View framework

Understanding the Qt OpenGL module

Qt OpenGL and Qt Widgets

Graphics in Qt Quick

Qt OpenGL and Qt Quick

Custom Qt Quick items using QPainter

Understanding the Qt Quick scene graph

Qt Quick scene graph structure

Rendering using a scene graph

Using a scene graph with the Native Graphics

3D graphics with Qt Quick 3D

Shader effects

Using the Canvas QML type

Understanding particle simulations

Animation in Qt Widgets

Animation and transitions in Qt Quick

Controlling animations

States, state machine, and transitions in Qt Quick

The state machine in Qt Widgets

Summary

Chapter 9: Testing and Debugging

Technical requirements

Debugging in Qt

Debuggers supported by Qt

Debugging strategies

Debugging a C++ application

Debugging a Qt Quick application

Testing in Qt

Unit testing in Qt

Integrating with Google's C++ testing framework

Testing Qt Quick applications

GUI testing tools

The Linux Desktop Testing Project (LDTP)

GammaRay

Squish

Summary

Chapter 10: Deploying Qt Applications

Technical requirements

Understanding the need for deployment

Choosing between static and dynamic libraries

Deploying on desktop platforms

Deploying on Windows

Windows deployment tool

Deploying on Linux

Deploying on macOS

Using the Qt Installer Framework

Deploying on Android

Other installation tools

Summary

Chapter 11: Internationalization

Technical requirements

Understanding internationalization and Qt Linguist

Writing source code for translation

Loading translations in a Qt application

Switching languages dynamically

Internationalization with Qt Widgets

Adding dynamic translation to a Qt Widgets application

Internationalization with Qt Quick

Translating dynamically in a Qt Quick application

Deploying translations

Summary

Chapter 12: Performance Considerations

Technical requirements

Understanding performance optimization

Optimizing C++ code

Using concurrency, parallelism, and multithreading

Profiling a Qt Quick application using QML Profiler and Flame Graph

Other Qt Creator analysis tools

Optimizing graphical performance

Creating benchmarks

Different analysis tools and optimization strategies

Memory profiling and analysis tools

Optimizing during linking

Building a Qt application faster

Performance considerations for Qt Widgets

Learning best practices of QML coding

Summary

Why subscribe?

Other Books You May Enjoy

Preface

Qt is a cross-platform application development framework designed to create great software applications with amazing user interfaces for desktop, embedded, and mobile platforms. It provides developers with a great set of tools for designing and building great applications without having to worry about platform dependency.

In this book, we will focus on Qt 6, the latest version of the Qt framework. This book will help you with creating user-friendly and functional graphical user interfaces. You will also gain an advantage over competitors by providing better-looking applications with a consistent look and feel across different platforms.

Developers who want to build a cross-platform application with an interactive GUI will be able to put their knowledge to work with this practical guide. The book provides a hands-on approach to implementing the concepts and associated mechanism that will have your application up-and-running in no time. You will also be provided explanation for essential concepts with examples to give you a complete learning experience.

You will begin by exploring the Qt framework across different platforms. You will learn how to configure Qt on different platforms, understand different Qt modules, learn core concepts, and learn how they can be used to build efficient GUI applications. You will be able to build, run, test, and deploy applications across different platforms. You will also learn to customize the look and feel of the application and develop a translation aware application. Apart from learning the complete application process, the book will also help you in identifying the bottlenecks and how to address them in order to enhance the performance of your application.

By the end of this book, you will be able to build and deploy your own Qt applications on different platforms.

Who this book is for

This book is intended for developers and programmers who want to build GUI-based applications. It is also intended for software engineers who have coded in C++ before. The entry barrier isn't that high, so if you understand basics C++ and OOPS concepts, then you can embark on this journey.

In addition, this book can help intermediate-level Qt developers, who want to build and deploy in other platforms. Working professionals or students, who want to get started with Qt programming, as well as programmers who are new to Qt, will find this book useful.

What this book covers

Chapter 1, Introduction to Qt 6, will introduce you to Qt and describe how to set it up on a machine. By the end of the chapter, readers will be able to build Qt from source code and get started on their platform of choice.

Chapter 2, Introduction to Qt Creator, introduces you to the Qt Creator IDE and its user interface. This chapter will also teach you how to create and manage projects in Qt Creator. You will learn to develop a simple Hello World application using Qt Creator and learn about different shortcuts, and practical tips.

Chapter 3, GUI Design Using Qt Widgets, explores the Qt Widgets module. Here, you will learn the various kinds of widgets that are available for creating GUIs. You will also be introduced to Layouts, Qt Designer, and learn how to create your own custom controls. This chapter will help you in developing your first GUI application using Qt.

Chapter 4, Qt Quick and QML, covers fundamentals of Qt Quick and QML, Qt Quick Controls, Qt Quick Designer, Qt Quick Layouts, and Basic QML Scripting. In this chapter, you will learn to use Qt Quick controls and how to integrate C++ code with QML. By the end of this chapter, you will be able to create a modern application with fluid UI using QML.

Chapter 5, Cross-Platform Development, explores cross-platform development using Qt. You will learn about different settings in Qt Creator. In this chapter, you will be able to run sample applications on your favorite desktop and mobile platforms.

Chapter 6, Signals and Slots, covers the signals and slots mechanism in depth. You will be able to communicate between different C++ classes and between C++ and QML. You will also learn about events, event filters and event loop.

Chapter 7, Model View Programming, introduces you to the Model/View architecture in Qt and its core concepts. Here, you will be able to write custom models and delegates . You can use these to display required information on your Qt Widget-based or Qt Quick-based GUI application.

Chapter 8, Graphics and Animations, introduces the concepts of 2D graphics and animations. You will learn how to use painter APIs to draw different shapes on the screen. We will further discuss the possibility of graphics data representation using Qt's Graphics View framework and Scene Graph. This chapter will guide you towards creating an attention-grabbing user interface with animations. The chapter also touches upon the state machine framework.

Chapter 9, Testing and Debugging, explores different debugging techniques for a Qt application. You will learn about unit testing and the Qt Test framework in this chapter. We will also discuss how to use the Google Test framework with Qt Test, as well as learn about the available Qt tooling and GUI specific testing techniques.

Chapter 10, Deploying Qt Applications, discusses the importance of software deployment. You will learn to deploy a Qt application on various platforms, including desktop and mobile platforms. You will learn about the available deployment tools and steps to create an installer package.

Chapter 11, Internationalization, introduces you to internationalization. Qt provides excellent support for translating Qt Widgets and Qt Quick applications into local languages. In this chapter, you will learn how to make an application with multi-lingual support. You will also learn about inbuilt tools and various considerations for making a translation-aware application.

Chapter 12, Performance Considerations, introduces you to performance optimization techniques and how to apply them in the context of Qt programming. Here, we will discuss different profiling tools to diagnose performance problems, concentrating specifically on the tools available on Windows. In this chapter, you will learn how to profile performance with QML Profiler and benchmark your code. The chapter will also help you write high-performance optimized QML code.

To get the most out of this book

We will only use open source software, so you will not need to purchase any license. We will go over the installation procedures and detail as we progress through each chapter. To install the required software, you will require a functional internet connection and a desktop PC or laptop. Apart from that, there is no particular software requirement before you begin this book.

Important notes

For Android setup, you will need the following:

OpenJDK 8 (JDK-8.0.275.1)

Android SDK 4.0

NDK r21 (21.3.6528147)

Clang toolchain

Android OpenSSL

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

All code examples have been tested using Qt 6 on the Windows platform. You may see failures if you use Qt 5. However, they should work with future version releases too. Please make sure that the version you're installing to your computer is at least Qt 6.0.0 or later so that the code is compatible with the book.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Cross-Platform-Development-with-Qt-6-and-Modern-Cpp. Additionally, you can find some bonus examples with C++17 features in the aforementioned mentioned GitHub link. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781800204584_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Typically, the exec () method is used to show a dialog."

A block of code is set as follows:

    

    QMessageBox messageBox;

    messageBox.setText("This is a simple QMessageBox.");

    messageBox.exec();

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    

    QMessageBox messageBox;

    messageBox.setText("This is a simple QMessageBox.");

    messageBox.exec();

Any command-line input or output is written as follows:

> lrelease *.ts

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "The last step is to build and run the application. Hit the Run button in Qt Creator."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: The Basics

In this section, you will learn the basics and evolution of the framework and how to install Qt on different platforms. Throughout this section, you will learn more about the evolution of Qt. Then, we'll proceed to build our first example program using the latest version of Qt, which is Qt 6. You will be learning about the usage of the Qt Creator IDE. This section will introduce you to Qt Widgets, Qt Designer, and creating custom controls. You will learn about style sheets, QSS files, and theming. This section will also introduce you to Qt Quick and QML.

This section includes the following chapters:

Chapter 1, Introduction to Qt 6Chapter 2, Introduction to Qt CreatorChapter 3, GUI Design Using Qt WidgetsChapter 4, Qt Quick and QML

Chapter 1: Introduction to Qt 6

Qt (pronounced cute, not que-tee) is a cross-platform application development framework designed to create great software applications with uniform user interfaces (UIs) for desktop, embedded, and mobile platforms. It provides developers with a great set of tools to design and build great applications without worrying about platform dependency. In this chapter, you will learn the basics about the framework, its history, and how to install Qt on different platforms. You will learn what Qt is and why it is beneficial to use it. By the end of the chapter, you will be able to install Qt and get started on your platform of choice.

In this chapter, we're going to cover the following main topics:

Introducing QtReasons for using QtDownloading and installing QtBuilding Qt 6 from source

Technical requirements

To get started, you should have a desktop or laptop running on Windows, Linux, or macOS. Please use the updated Windows 10 or Ubuntu 20.04 long-term support (LTS). Alternatively, use the latest version of macOS (newer than macOS 10.14), such as macOS Catalina.

For your integrated development environment (IDE) to run smoothly, your system should have at least an Intel Core i5 processor along with a minimum of 4 gigabytes (GB) of random-access memory (RAM).

You will need an active internet connection to download and install Qt. As a prerequisite, you should also be familiar with C++ as Qt requires C++ programming knowledge.

Introducing Qt

Qt is a cross-platform software development framework for desktop, embedded, and mobile platforms. It follows the philosophy of code less, create more, and deploy everywhere. It supports platforms such as Windows, Linux, macOS, VxWorks, QNX, Android, iOS, and so on. The software also supports several microcontroller units (MCUs) from NXP, Renesas, and STMicroelectronics running on bare metal or FreeRTOS.

Qt was born as an attempt to provide a uniform graphical user interface (GUI) with the same look, feel, and functionality across different platforms. Qt accomplishes that by providing a framework to write code once and ensure that it runs on other platforms with minimal or no modifications. It is not a programming language, but rather a framework written in C++. The Qt framework and tools are dual-licensed under open source and commercial licenses.

Qt uses a modular approach to group related functionalities together. Qt Essentials are the foundation of Qt on all platforms. These modules are general and useful for most Qt-based applications. Essential modules are available for open source usage. Examples of Qt Essentials modules are Qt Core, Qt GUI, Qt QML, Qt Widgets, and so on. There are also special-purpose add-on modules that provide specific functionalities and come with certain license obligations. Examples of add-on modules are Qt 3D, Qt Bluetooth, Qt Charts, Qt Data Visualization, and more. As well as this, there are value-added modules such as Qt Automotive Suite, Qt for Device Creation, and Qt for MCUs, among others available under the commercial license.

To find out more about different Qt modules, visit https://doc.qt.io/qt-6/qtmodules.html.

Qt was released for public use in 1995. Since then, there have been many improvements and major changes. Qt 6 is the new major version of Qt. Its main goals are to remain prepared for the requirements coming in 2020 and beyond, remove obsolete modules, and be more maintainable. With this focus, there are architectural changes in Qt 6 that may break some level of backward compatibility with earlier versions.

Some essential modifications in Qt 6 are outlined here:

Introduction of strong typingJavaScript as an optional feature of Qt Modeling Language (QML)Removal of QML versioningRemoval of the duplicate data structures between QObject and QMLAvoidance of the creation of runtime data structuresCompilation of QML into efficient C++ and native codeSupport for hiding implementation detailsBetter integration of tools

Now that we've covered the basics, let's look at the main reasons for using Qt…

Reasons for using Qt

Qt is a modular, cross-platform application development framework. The biggest misunderstanding about Qt is that many people consider it as a GUI framework. However, Qt is much more than a GUI framework. It not only comprises a GUI module, but also a set of modules to make application development faster and easier to scale on various platforms. The biggest benefit of using Qt is its ability to provide portability to various platforms. Here are some advantages of using Qt for developers:

You can create incredible user experiences for your customers and boost your company brand using Qt.Cross-platform development saves both time and money. You can target multiple platforms with the same code base.Qt is known for making C++ easy and accessible. With Qt, developers can easily create high-performance, scalable applications with a fluid UI.Due to the open source model, the framework is future-proof, along with a great ecosystem.It further supports different programming languages and is a very flexible and reliable framework. Consequently, there are great companies such as Adobe, Microsoft, Samsung, AMD, HP, Philips, and MathWorks using Qt for their applications. Many open source projects such as VLC (previously known as VideoLAN Client), Open Broadcaster Software (OBS), and WPS Office (where WPS stands for Writer, Presentation, and Spreadsheets) are also built on Qt.

The core values of Qt are outlined as follows:

Cross-platform natureHighly scalableVery easy to useBuilt-in with world-class application programming interfaces (APIs), tools, and documentationMaintainable, stable, and compatibleA large community of users

Whether you are a hobbyist, a student, or working for a company, Qt provides great flexibility to use its modules as per your requirement. Many universities are using Qt as one of their coursework subjects. So, Qt is a great choice for programmers to start building new applications with ready-made features. Let's start by downloading and installing Qt 6 on your machine.

Downloading and installing Qt

There are different ways to install the Qt framework and tools on your system. You can download an online or offline installer from the Qt website, or you can build the source packages yourself. Qt recommends using the online installer for first-time installations and the Qt Maintenance Tool for modifying the installation later.

The installers allow you to download and install the following components:

Qt librariesQt Creator IDEDocumentation and examplesQt source codeAdd-On modules

The online installer allows you to select open source or commercial versions of Qt, tools, and Add-On modules to install based on the chosen license. The online installer doesn't contain the Qt components, but it is a downloader client to download all the relevant files. You can install once the download is complete. You will require a Qt account to download and install Qt. An evaluation version for the commercial Qt gives you free trial-period access, with all commercial packages and access to official Qt support. The installer requires you to sign in with your Qt account. If you don't have a Qt account, you can sign up during the installation process. The installer fetches the license attached to the account from the Qt server and lists down modules according to your license. If you are new to Qt, then we recommend that you start with the open source version.

The offline installer is a platform-specific package that includes all Qt modules and add-ons relevant for the platform. Due to the official policy changes, open source offline installers are not available any more since Qt 5.15. If you have a commercial license, then you can provide the credentials during the installation process. You can locate your license key in your Qt account web portal.

You can download them from the following links:

Open source: https://www.qt.io/download-open-sourceCommercial: https://www.qt.io/downloadOffline: https://www.qt.io/offline-installers

Important note

The Qt Company provides users with a dual-licensing option. As a beginner, you can get started with an open source license to explore Qt. If you are working for a company, then discuss with your manager or Information Technology (IT) or legal team to procure a commercial license or to understand legal obligations. You can learn more about Qt licensing at https://www.qt.io/licensing/.

Downloading Qt

Let's start by downloading Qt onto your machine, as follows:

To begin, visit the https://www.qt.io/download download page.Click on the Download. Try. Buy. button in the top-right corner. You will see different download options here.If you want to try the commercial version, then click on Try Qt section. If you already have a Qt account, then you can log in into the account under the Existing customers section.Considering that you are new to Qt, we will begin with the open source version. Click on the Go open source button, as shown in the following screenshot:

Figure 1.1 – Qt website download options

On the next screen, you will find Download the Qt Online Installer button. Click on it to proceed to the download link.The web page will automatically detect the underlying platform details from the browser and will show you the Download button. You can also select your intended installer by choosing the other options: you can select 32-bit or 64-bit or download for a different platform.

You will see a Thank you page after you click on the download option. At this stage, you can find the installer in your download folder.

Next, let's begin with the installation process on the Windows platform.

Installing Qt on Windows

Now, let's start the installation process on Windows! Proceed as follows:

You will find a file with the name qt-unified-windows-x86-%VERSION%-online.exe inside your download folder. Double-click on the executable, and you will see a Welcome screen.Click the Next button, and a credentials screen will appear, asking you to log in with your Qt account. If you don't have one, then you can sign up on the same page, as shown in the following screenshot:

Figure 1.2 – Login screen of the installer

In the next screen, you will be presented with the open source usage obligations agreement. You won't get this screen if you are installing using a commercial license. Click on the first checkbox, saying I have read and approve the obligations of using Open Source Qt, and acknowledge that you are not using Qt for commercial purposes. Make sure you read the terms and conditions mentioned in the agreement! Then, click on the Next button.The next screen will provide you with options related to tracking and sharing pseudonymous data in Qt Creator. You may allow or disable these options based on your preferences. Then, click on the Next button to proceed to the next screen.In the next screen, you can specify the installation path. You may continue with the default path, or you can change it to any other path if you don't have enough space on the default drive. You can also choose whether you want to associate common file types with Qt Creator by selecting the checkbox option at the bottom. Click on the Next button.Next, you will be presented with a list where you can select the version(s) of Qt you need to install on your system. You may simply proceed with the default options. If you don't need some of the components, then you can unselect them to reduce the size of the download. You can update the Qt components using the Maintenance Tool anytime later. To complete the installation process, click on the Next button. The component selection screen can be seen here:

Figure 1.3 – Component selection screen of the installer

In the next screen, you will be presented with the license agreement. Click on the first radio button, which says I have read and agree to the terms contained in the license agreements. Again, make sure you read the terms and conditions mentioned in the license agreement, and then click on the Next button.On the next screen, you can create Start menu shortcuts on Windows. This screen will not be available for other platforms. Once you have finished doing this, click on the Next button.Now, Qt is ready to be installed in your system. Make sure you have a working internet connection and data balance. Click on the Install button to begin the installation. The download process will take time, depending on your internet speed. Once the required files are downloaded, the installer will automatically install them in the previously selected path.Once the installation is finished, the installer will make an entry for the Maintenance Tool, which will help you later to make changes to the libraries. Click on the Next button to move to the last screen of the installer.In order to complete the installation process, click on the Finish button. If you have left the Launch Qt Creator checkbox checked, then Qt Creator will be launched. We will discuss this in more detail in the next chapter. Now, Qt is ready to be used on your Windows machine. Click on the Finish button to exit the wizard.

Installing Qt on Linux

Now, let's install the Qt framework on the latest LTS version of Linux, such as Ubuntu 20.04, CentOS 8.1, or openSUSE 15.1. We will be focusing on the most popular Linux distribution, Ubuntu. You can follow the same steps as mentioned previously to download the online installer from the Qt website.

On Ubuntu, you will get an installer file such as qt-unified-linux-x64-%VERSION%-online.run, where %VERSION% is the latest version— for example: qt-unified-linux-x86-4.0.1-1-online.run.

You may have to give write permissions to the downloaded file before executing it. To do that, open the terminal and run the following command:

$ chmod +x qt-unified-linux-x64-%VERSION%-online.run

You can start the install process by double-clicking the downloaded installer file. The installation requires superuser access. You may have to add a password in the authorization dialog during the installation. You can also run the installer from the terminal, as follows:

$ ./qt-unified-linux-x64-%VERSION%-online.run

You will see similar screens to those shown for the Windows platform. Apart from the operating system (OS)-specific title bar changes, all the screens remain the same for installation in Ubuntu or similar Linux flavors.

At the time of writing the book, there was no Ubuntu or Debian package available for Qt 6 as the respective maintainers have stepped down. Hence, you may not get the Qt 6 package from the terminal.

Installing Qt on macOS

If you are a macOS user, then you can also install the same way as discussed for the earlier platforms. You can follow the same steps mentioned previously to download the online installer from the Qt website.

You will get an installer file such as qt-unified-mac-x64-%VERSION%-online.dmg, where %VERSION% is the latest version (such as qt-unified-mac-x64-4.0.1-1-online.dmg).

Qt has a dependency on Xcode. To install Qt on your Mac, you will need Xcode installed on your machine, otherwise, it will refuse to install. If you are an Apple developer, then your Mac may have Xcode installed. If you don't have Xcode installed on your machine, then you may proceed to install Xcode's Command Line Tools instead of Xcode. This will save time and storage space on your machine:

To begin, type the following command on the terminal:

$ xcode-select --install    

If the terminal shows the following output, then your system is ready for the next steps:

xcode-select: error: command line tools are already installed, use

"Software Update" to install updates

The next step is to install the Qt framework. Double-click on the installer file to launch the installation interface.If the installer still complains that Xcode is not installed, then keep clicking OK until the message goes away permanently. Remember the installation path. Once the installation is finished, you are ready to use Qt on your machine.

Further instructions on Qt for macOS can be found at the following link:

https://doc.qt.io/qt-6/macos.html

Updating or removing Qt

Once Qt is installed, you can modify the components—including updating, adding, and removing components—using the Maintenance Tool under the installation directory. The directory structure remains the same for all desktop platforms. The installation directory contains folders and files, as shown in the following screenshot (on Windows):

Figure 1.4 – The Maintenance Tool inside the installed folder

Let's begin with the maintenance process! You can add, remove, and update modules using the Maintenance Tool. Proceed as follows:

Click on the MaintenanceTool.exe executable to launch the maintenance interface. Click on the Next button, and a credentials screen will appear, asking you to log in with your Qt account. The login details will be prefilled from your last login session. You can click Next to add or update components or select the Uninstall only checkbox to remove Qt from your system. The following screenshot shows what the credentials screen looks like:

Figure 1.5 – Welcome screen of the Maintenance Tool

Once you are logged in, the tool will present you with options to add or remove or update the components, as shown in the following screenshot. Click on the Next button to proceed further:

Figure 1.6 – Setup screen of the Maintenance Tool

On the next screen, you can select new components from the latest releases or the archived version. You can click on the Filter button to filter versions as per your requirement. You can also add new platform-specific components such as Android from the component list. If the component is existing and you uncheck it, then it will be removed from your desktop during the update. Once you have selected the components, click on the Next button. The following screenshot shows what the component selection screen looks like:

Figure 1.7 – Component selection screen

You will then come across the update screen. This screen will tell you how much storage space is required for the installation. If you are running out of storage space, then you may go back and remove some existing components. Click on the Update button to begin the process, as illustrated in the following screenshot:

Figure 1.8 – The Ready to Update screen of the Maintenance Tool

You can abort the update installation process by clicking on the Cancel button. Qt will warn you and ask you for confirmation before aborting the installation process, as illustrated in the following screenshot. Once the process is aborted, click on the Next button to exit the wizard:

Figure 1.9 – The cancel dialog

Launch the Maintenance Tool again to update existing components from the latest releases. You can click on the Quit button to exit the Maintenance Tool. Please wait while the installer fetches the meta-information from the remote repository. Click on the Next button to see the available components. The update option is illustrated in the following screenshot:

Figure 1.10 – The Update option in the Maintenance Tool

Next, you can select which components to update from the checkboxes. You can choose to update all or you can update selectively. The installer will show how much storage space will be required for the update, as illustrated in the following screenshot. You can click Next to go to the update screen and begin the update. Then, on the next screen, click on the Update button to download the update packages:

Figure 1.11 – Components available for update

Once the installation is finished, the installer makes entries for the Maintenance Tool, which will help you make changes to the libraries later. This is illustrated in the following screenshot. Click on the Next button to move to the last screen of the installer:

Figure 1.12 – The Update finished screen in the Maintenance Tool

In the last screen, you will see Restart and Finish buttons. Click on the Finish button to exit the Qt wizard.Similarly, you can restart or launch the Maintenance Tool and select the Remove all components radio button. Click on the Next button to begin the uninstallation process, as illustrated in the following screenshot:

Figure 1.13 – The Remove option in the Maintenance Tool

Please note that on clicking the Uninstall button, all the Qt components will be removed from your system; you will have to reinstall Qt if you want to use them again. Click on Cancel if you don't intend to remove the Qt components from your system, as illustrated in the following screenshot. If you intend to remove the existing version and use a newer version of Qt, then select the Add or remove components option, as discussed earlier. This will remove older Qt modules and free up your disk space:

Figure 1.14 – The Uninstall screen in the Maintenance Tool

In this section, we learned about modifying an existing Qt installation through the Maintenance Tool. Now, let's learn how to build and install Qt from the source code.

Building Qt 6 from source

If you want to build the framework and tools yourself or experiment with the latest unreleased code, then you can build Qt from the source code. If you're going to develop a specific Qt version from the source, then you can download the Qt 6 source code from the official releases link, as shown here: https://download.qt.io/official_releases/qt/6.0/.

If you are a commercial customer, then you can download the Source Packages from your Qt account portal. Platform-specific building instructions are discussed in the upcoming subsections.

You can also clone from the GitHub repository, and check out the desired branch. At the time of authoring this book, the Qt 6 branch remained inside the Qt 5 super module. You can clone the repository from the following link: git://code.qt.io/qt/qt5.git.

The qt5.git repository may get renamed to qt.git in the future for maintainability. Please refer to the QTQAINFRA-4200 Qt ticket. Detailed instructions on how to build Qt from Git can be found at the following link: https://wiki.qt.io/Building_Qt_6_from_Git.

Ensure that you install the latest versions of Git, Perl, and Python on your machine. Make sure there is a working C++ compiler before proceeding to the platform-specific instructions in the next section.

Installing Qt on Windows from source

To install Qt 6 on Windows from source code, follow these next steps:

First of all, download the source code from Git or from the open source download link mentioned earlier. You will get a compressed file as qt-everywhere-src--%VERSION%.zip, where %VERSION% is the latest version (such as qt-everywhere-src-6.0.3.zip). Please note that suffixes such as -everywhere-src- may get removed in the future.Once you have downloaded the source archive, extract it to a desired directory—for example, C:\Qt6\src.In the next step, configure the build environment with a supported compiler and the required build tools.Then, add the respective installation directories of CMake, ninja, Perl, and Python to your PATH environment variable.The next step is to build the Qt library. To configure the Qt library for your machine type, run the configure.bat script in the source directory.In this step, build Qt by typing the following command in Command Prompt:

>cmake --build . –parallel

Next, enter the following command in Command Prompt to install Qt on your machine:

>cmake --install .

Your Windows machine is now ready to use Qt.

To understand more about the configure options, visit the following link:

https://doc.qt.io/qt-6/configure-options.html

Detailed build instructions can be found at the following link:

https://doc.qt.io/qt-6/windows-building.html

Installing Qt on Linux from source

To build the source package on Linux distributions, run the following set of instructions on your terminal:

First of all, download the source code from Git or from the open source download link mentioned earlier. You will get a compressed file as qt-everywhere-src--%VERSION%.tar.xz, where %VERSION% is the latest version (such as qt-everywhere-src-6.0.3.tar.xz). Please note that suffixes such as -everywhere-src- may get removed in the future.Once you have downloaded the source archive, uncompress the archive and unpack it to a desired directory—for example, /qt6, as illustrated in the following code snippet:

$ cd /qt6

$ tar xvf qt-everywhere-opensource-src-%VERSION%.tar.xz

$ cd /qt6/qt-everywhere-opensource-src-%VERSION%

To configure the Qt library for your machine, run the ./configure script in the source directory, as illustrated in the following code snippet:

$ ./configure

To create the library and compile all the examples, tools, and tutorials, type the following commands:

$ cmake --build . --parallel

$ cmake --install .

The next step is to set the environment variables. In .profile (if your shell is bash, ksh, zsh, or sh), add the following lines of code:

PATH=/usr/local/Qt-%VERSION%/bin:$PATH

export PATH

In .login (if your shell is csh or tcsh), add the following line of code:

setenv PATH /usr/local/Qt-%VERSION%/bin:$PATH

If you use a different shell, modify your environment variables accordingly. Qt is now ready to be used on your Linux machine.

Detailed building instructions for Linux/X11 can be found at the following link:

https://doc.qt.io/qt-6/linux-building.html

Installing Qt on macOS from source

Qt has a dependency on Xcode. To install Qt on your Mac, you will need Xcode installed on your machine. If you don't have Xcode installed on your machine, then you may proceed to install Xcode's Command Line Tools:

To begin, type the following command on the terminal:

$ xcode-select --install    

If the terminal shows the following output, then your system is ready for the next steps:

xcode-select: error: command line tools are already installed, use

"Software Update" to install updates

To build the source package, run the following set of instructions on your terminal:

$ cd /qt6

$ tar xvf qt-everywhere-opensource-src-%VERSION%.tar          

$ cd /qt6/qt-everywhere-opensource-src-%VERSION%

To configure the Qt library for your Mac, run the ./configure script in the source directory, as illustrated in the following code snippet:

$ ./configure  

To create a library, run the make command, as follows:

$ make

If -prefix is outside the build directory, then type the following lines to install the library:

$ sudo make -j1 install

The next step is to set the environment variables. In .profile (if your shell is bash), add the following lines of code:

PATH=/usr/local/Qt-%VERSION%/bin:$PATH

export PATH

In .login (if your shell is csh or tcsh), add the following line of code:

setenv PATH /usr/local/Qt-%VERSION%/bin:$PATH

Your machine is now ready for Qt programming.

Detailed building instructions for macOS can be found here:

https://doc.qt.io/qt-6/macos-building.html

In this section, we learned how to install Qt from source on your favorite platform. Now, let's summarize our learning.

Summary

This chapter explained the basics of the Qt framework and what it can be used for. Here, we discussed the history, different modules, and advantages of using Qt. We also learned about different methods of installation with license obligations, giving step-by-step installation procedures for Qt on different desktop platforms. Now, your machine is ready to explore Qt.

In the next chapter, we will discuss the Qt Creator IDE. You will learn about the UI of the IDE, different configurations, and how to use it for your Qt project.

Chapter 2: Introduction to Qt Creator

Qt Creator is Qt's own Integrated Development Environment (IDE) for cross-platform application development. In this chapter, you will learn the basics of the Qt Creator IDE as well as covering the user interface (UI) of the IDE. We will also look at how to create and manage projects in Qt Creator. This module of Qt covers developing a simple Qt application using Qt Creator, shortcuts, and practical tips for developers.

More specifically, we're going to cover the following main topics:

Basics of Qt CreatorConfiguring the IDE and managing projectsUser interfacesWriting a sample applicationAdvanced options

Qt Creator can make your Qt learning easier with many useful tools and examples. You will need minimal IDE knowledge to get started. By the end of this chapter, you will be familiar with the use of Qt Creator. You will also be able to build and run your first Qt application on your favorite desktop platform, as well as being aware of the advanced options available in the IDE, which you will be able to customize in line with your preferences.

Technical requirements

The technical requirements for this chapter are the same as Chapter 1, Introduction to Qt 6. You will need the latest Qt version, namely Qt 6.0.0 MinGW 64-bit, Qt Creator 4.13.0 or higher, and Windows 10, Ubuntu 20.04 LTS, or the latest version of macOS (higher than macOS 10.13 at a minimum) such as macOS Catalina. Qt supports earlier versions of operating systems such as Windows 8.1 or Ubuntu 18.04. However, we recommend you upgrade to the latest version of your preferred operating system to ensure smooth functioning. In this chapter, we have used screenshots from the Windows 10 platform.

Exploring the Qt Creator UI

Qt Creator is an IDE produced by the Qt Company. It integrates multiple tools including a code editor, a Graphical UI (GUI) designer, a compiler, a debugger, Qt Designer, Qt Quick Designer, and Qt Assistant, among others.

Qt Designer helps in designing widget-based GUIs whereas Qt Quick Designer provides a UI to create and edit QML-based GUIs in Design Mode. Qt Assistant is an integrated documentation viewer that opens contents related to a given Qt class or function with the press of the F1 key.

Let's begin by launching Qt Creator. The binary can be found inside Qt\Tools\QtCreator\bin. You will see a screen like that shown in Figure 2.1:

Figure 2.1 – Qt Creator interface

You can see the following GUI sections in the UI:

IDE menu bar: This provides