Chapter 1. Overview of the Qt Class Hierarchy

If you want to get to know an area,
you must first study the map.

— Tony Buzan

Your First Qt Application

To write and run your first Qt application, you must have the Qt library and all required dependencies installed. If you have not done so yet, refer to Appendix 1 of this book for installation instructions.

Everything is now ready to go! Following tradition, it is time to say hello — and to make sure no one is left out, we will address the entire world at once. Let’s write a short “Hello, World!” program whose output is shown in Fig. 1.1.

Qt "Hello, World!" application window showing a label with greeting text
Fig. 1.1. The “Hello, World!” application window

Writing this type of program has become a tradition when getting acquainted with a new language or library. Although such an example cannot demonstrate the full potential of the library, it introduces the fundamental concepts and gives a sense of the effort required to build applications with a given framework. It also lets you verify that everything needed for compilation and linking has been installed correctly.

Listing 1.1. The “Hello, World!” program (file hello.cpp)

#include <QtWidgets>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QLabel lbl("Hello, World !");
    lbl.show();
    return app.exec();
}

The first line of Listing 1.1 includes the QtWidgets aggregate header file, which is a module that bundles the header files for all classes used in our program — QApplication and QLabel — making the example compact and easy to read. Using this aggregate include is perfectly reasonable in tutorial examples and small demonstrations, since it keeps the code shorter and more approachable. However, in real-world, large-scale projects it is preferable to include only the specific header files you actually need. Explicit includes reduce the amount of data passed to the compiler and help track dependencies more precisely.

File Archive

You can download the file archive with the examples for this book from the following link: https://qt-book.com/examples/Max_Schlee-Qt_6_9_Book-Examples.zip (see Appendix 4). The files mentioned in the listing names are located in folders corresponding to the respective chapter numbers.

Let’s take a closer look at the example. First, an object of the QApplication class is created; this object manages the application. Its constructor requires two arguments: the first is the count of command-line arguments passed to the program, and the second is a pointer to an array of character strings containing those arguments, one per entry. Every Qt application with a graphical user interface must create exactly one instance of this class, and that instance must be created before any user-interface operations are performed.

Next, an object of the QLabel class is created. Qt controls are invisible by default after construction, so the show() method must be called to display them. The QLabel object serves as the primary control of the application, which means the application will exit when its window is closed. If an application happens to have multiple independent top-level controls, the application will terminate when the window of the last such control is closed. This is the correct behavior — otherwise the application would remain in memory and continue consuming system resources.

Finally, on the last line, the application is started by calling QApplication::exec(). This call activates the event loop defined in the QCoreApplication class, which is the base class for QGuiApplication, from which QApplication inherits. This loop dispatches events received from the operating system to the appropriate objects. It continues running until either the static method QCoreApplication::exit() is called or the window of the last control is closed. When the application finishes, QApplication::exec() returns an integer value containing the exit code.

Qt Modules

Developers who are just beginning to learn a new library’s class hierarchy often feel overwhelmed by the sheer volume of information to absorb. However, the Qt class hierarchy has a clear internal structure that is important to understand early on, so you can navigate the library confidently and intuitively.

The Qt library comprises roughly 1,800 classes that cover a large portion of operating-system functionality, providing developers with powerful mechanisms that both extend and simplify application development — without violating the philosophy of the underlying operating system. Qt is not a monolithic whole; it is divided into modules that form a logical dependency structure (Table 1.1).

Table 1.1. Selected Qt Modules

Library Project file identifier (qmake / CMake) Purpose
QtCore core / Qt6::Core The foundational module consisting of non-GUI classes (see Parts I, IV)
QtGui Gui / Qt6::Gui Base classes for GUI programming
QtWidgets widgets / Qt6::Widgets Extends QtGui with C++ widget-based UI building blocks (see Parts II, III, IV, V)
QtQuick quick / Qt6::Quick A declarative framework for rapid next-generation UI development (see Part VIII)
QtQML qml / Qt6::Qml The engine for the QML and JavaScript languages (see Part VIII)
QtNetwork network / Qt6::Network Networking module for TCP, UDP, HTTP, and FTP programming (see Chapter 39)
QtSql sql / Qt6::Sql Database programming module (see Chapter 41)
QtSvg svg / Qt6::Svg Module for working with SVG (Scalable Vector Graphics) (see Chapter 22)
QtXml xml / Qt6::Xml XML support module with SAX and DOM interfaces (see Chapter 40)
QtHttpServer httpserver Module for building HTTP servers (see Chapter 39)
QtMultimedia multimedia / Qt6::Multimedia Multimedia module: audio, video, camera, and radio support (see Chapter 27)
QtMultimediaWidgets multimediawidgets / Qt6::MultimediaWidgets Widget-based UI components for QtMultimedia (see Chapter 27)
QPrintSupport printsupport / Qt6::PrintSupport Printer support module (see Chapter 24)
QtTest test / Qt6::Test Unit testing framework (see Chapter 45)
QtConcurrent concurrent High-level API for multithreaded programming (see Chapter 38)

Every Qt program uses at least the three modules from Listing 1.1 — QtCore, QtGui, and QtWidgets — which are present in every GUI application and are therefore included by the build-system generator by default (see Chapter 3). Qt 6 supports two build utilities: qmake and CMake. Both are discussed in detail in Chapter 3; for now, here is a quick demonstration. For example, if your application requires additional functionality, you can add the necessary modules to your project file:

QT += widgets network sql

To exclude a module from the project:

QT -= gui

For CMake-based projects, modules are specified in the find_package call (capitalized) and then linked to your target:

find_package(Qt6 REQUIRED COMPONENTS Widgets Network Sql)
target_link_libraries(<your_target> PRIVATE Qt6::Widgets Qt6::Network Qt6::Sql)

where <your_target> is the name of your build target.

It is also worth noting that CMake is the preferred build tool in Qt 6.

The most significant module listed in Table 1.1 is QtCore, as it serves as the foundation for all other modules. The modules that depend directly on QtCore are: QtNetwork, QtGui, QtSql, and QtXml.

For each module, Qt provides a single aggregate header file containing the headers for all classes in that module. The name of this header matches the module name. For example, to include the QtWidgets module, add the following line to your program, just as we did in Listing 1.1:

#include <QtWidgets>

The Qt Namespace

The Qt namespace contains a number of enumeration types and constants that are frequently used in Qt programming. To access a constant from this namespace, you must prefix it with Qt (for example, use Qt::red instead of red). If you prefer to omit the Qt prefix, add the following directive at the top of your source file:

using namespace Qt;

The QtCore Module

QtCore is the foundational module. It underlies all Qt applications and contains no user-interface classes. If you are building a console application, this single module may be all you need. QtCore includes more than 250 classes, among them:

  • Container classes: QList, QMap, QVariant, QString, etc. (see Chapter 4);
  • I/O classes: QIODevice, QTextStream, QFile (see Chapter 36);
  • The process class QProcess and threading classes: QThread, QWaitCondition, QMutex, QSemaphore (see Chapter 38);
  • Timer classes: QBasicTimer and QTimer (see Chapter 37);
  • Date and time classes: QDate, QTime, QDateTime (see Chapter 37);
  • The QObject class — the cornerstone of the Qt object model (see Chapter 2);
  • The base event class QEvent (see Chapter 14);
  • The application settings class QSettings (see Chapter 28);
  • The application class QCoreApplication, whose instance can run an event loop when needed;
  • Animation support classes: QAbstractAnimation, QVariantAnimation, etc. (see Chapter 22);
  • State machine classes: QStateMachine, QState, etc. (see Chapter 22);
  • Item-model classes: QAbstractItemModel, QStringListModel, QAbstractProxyModel (see Chapter 12);
  • JSON classes: QJsonDocument, QJsonObject, QJsonArray, QJsonValue (see Chapter 40);
  • Regular expression classes: QRegularExpression, QRegularExpressionMatch (see Chapter 4).

The module also includes support mechanisms for resource files (see Chapter 3).

Let’s take a closer look at the QCoreApplication class. The application object QCoreApplication can be thought of as a container that holds objects connected to the operating system context. The lifetime of a QCoreApplication instance matches the lifetime of the entire application, and it remains accessible at any point during program execution. A QCoreApplication object must be created exactly once per application. Its responsibilities include:

  • Managing events between the application and the operating system;
  • Forwarding and providing access to command-line arguments;
  • Managing the application lifecycle.

In addition, QCoreApplication can be subclassed to override certain methods, and its instance can serve as a holder for additional global data used within the application. This approach can help you avoid the undesirable use of the Singleton design pattern.

The QtGui Module

This module provides classes for integration with the windowing system, OpenGL, and Vulkan. It includes the QWindow class, which represents a basic surface capable of receiving user-input events, focus changes, and resize events, as well as supporting drawing and graphics operations on its surface.

The application class for this module is QGuiApplication. It provides an event loop and additionally supports:

  • Access to the clipboard (see Chapter 29);
  • Initialization of application-wide settings — such as the color palette for UI controls (see Chapter 13);
  • Cursor shape management.

The QtWidgets Module

This module contains roughly 350 widget classes that serve as the building blocks for GUI programming. Some highlights:

  • The QWidget class — the base class for all Qt controls. Visually it is nothing more than a filled rectangle, but behind that simplicity lies a rich set of non-trivial capabilities. The class has approximately 300 methods and more than 60 properties. It receives dedicated coverage in Chapter 5;
  • Layout classes: QVBoxLayout, QHBoxLayout, QGridLayout (see Chapter 6);
  • Display widget classes: QLabel, QLCDNumber (see Chapter 7);
  • Button classes: QPushButton, QCheckBox, QRadioButton (see Chapter 8);
  • Range-control classes: QSlider, QScrollBar (see Chapter 9);
  • Input classes: QLineEdit, QSpinBox (see Chapter 10);
  • Selection classes: QComboBox, QToolBox (see Chapter 11);
  • Menu classes: QMainWindow and QMenu (see Chapters 31 and 34);
  • Message box and dialog classes: QMessageBox, QDialog (see Chapter 32);
  • Drawing classes: QPainter, QBrush, QPen, QColor (see Chapter 18);
  • Raster image classes: QImage, QPixmap (see Chapter 19);
  • Style classes (see Chapter 26) — both individual controls and the entire application can be assigned a style that changes their visual appearance;
  • The application class QApplication, which provides the event loop.

Let’s look more closely at the last item — the QApplication class, which we encountered in the very first example. Everything said earlier about QCoreApplication applies equally to QApplication, since the latter is its descendant. A QApplication object serves as the central control point for Qt applications with a widget-based user interface. This object is responsible for receiving keyboard, mouse, timer, and other events that the application must handle appropriately. For example, even the simplest application window can be resized or obscured by another application’s window, and all such events require a correct response.

QApplication inherits directly from QGuiApplication and extends it with the following capabilities:

  • Application style management. This enables setting the look and feel of the application, including custom styles (see Chapter 26);
  • Obtaining a pointer to the desktop object (desktop);
  • Managing global mouse behavior (such as the double-click interval) and tracking mouse movement inside and outside the application window;
  • Ensuring proper application shutdown when the operating system exits (see Chapter 28).

Sometimes an application may be inactive while it needs to draw the user’s attention. For this purpose, the QApplication class provides the static method alert(). Calling it will cause the application icon to bounce in the Dock on macOS (Fig. 1.2) and pulse in the taskbar on Windows (Fig. 1.3).

Application icon bouncing in the macOS Dock after calling QApplication::alert()
Fig. 1.2. Application icon bouncing in the macOS Dock
Application icon pulsing in the Windows taskbar after calling QApplication::alert()
Fig. 1.3. Application icon pulsing in the Windows taskbar

The QtQuick and QtQML Modules

These are an alternative to widgets — a set of technologies for the rapid development of next-generation graphical interfaces based on the declarative QML language, the JavaScript programming language, and the full capabilities of the Qt library (see Chapter 53).

The QtNetwork Module

The QtNetwork module provides tools for TCP and UDP socket programming (classes QTcpSocket and QUdpSocket), as well as client applications using the HTTP and FTP protocols (class QNetworkAccessManager). This module is covered in Chapter 39.

The QtXml Module

The QtXml module is designed for working with core XML functionality through SAX2 and DOM interfaces as defined by Qt’s classes (see Chapter 40).

The QtSql Module

This module is designed for database programming. It includes classes that enable manipulation of database values (see Chapter 41).

The QtMultimedia and QtMultimediaWidgets Modules

The QtMultimedia module provides everything needed to build multimedia-capable applications. It supports both low-level access for fine-grained, specialized implementations and a high-level API that enables audio and video playback in just a few lines of code. The QtMultimediaWidgets module provides ready-to-use widget-based components that save implementation time. Both modules are covered in detail in Chapter 27.

The QtSvg Module

This module adds support for the SVG vector graphics format, which is based on XML. The format supports not only static vector image rendering but can also be used for vector animation (see Chapter 22).

Additional Qt Modules

In addition to its essential modules, Qt also provides optional add-on modules intended for a narrower audience of developers (Table 1.2). Some of these modules must be explicitly selected during installation using the Qt Maintenance Tool (MaintenanceTool).

Table 1.2. Selected Qt Add-On Modules

Library Project file identifier (qmake / CMake) Purpose
QtWebEngineCore webenginecore / Qt6::WebEngineCore Enables seamless integration of web content into an application
QtWebEngineWidgets webenginewidgets / Qt6::WebEngineWidgets Provides ready-to-use widget-based web components and allows extending web content with custom widgets (see Chapter 46)
Qt 3D 3dcore, 3drenderer, 3dinput, 3dlogic, 3dextras, 3danimation, 3dquickscene2d / Qt6::3DCore, etc. A collection of 7 modules: Qt3DAnimation, Qt3DCore, Qt3DExtras, Qt3DInput, Qt3DLogic, Qt3DRender, and Qt3DScene2D. Their goal is to simplify 3D graphics programming
QtBluetooth Bluetooth / Qt6::Bluetooth Classes for Bluetooth wireless connectivity
QtLocation Location / Qt6::Location Geolocation classes for determining the current device location
QtSensors Sensors / Qt6::Sensors Access to mobile device sensors such as the orientation sensor and accelerometer. Currently supports iOS and Android
QtCharts Charts / Qt6::Charts Rendering data as stylish charts of varying complexity and types
QtDataVisualization Datavisualization / Qt6::DataVisualization Rendering data as 3D charts
QtRemoteObjects Remoteobjects / Qt6::RemoteObjects Inter-process communication (IPC) support. Provides a straightforward mechanism for exchanging data between applications on the same or remote machines
QtCore5Compat core5compat / Qt6::Core5Compat Compatibility module for deprecated Qt 5 APIs: includes classes and functions absent from Qt 6, for migrating legacy projects (see Chapter 48)

Summary

The Qt library is not monolithic — it is divided into individual modules: QtCore, QtGui, QtWidgets, QtQuick, QtQML, QtMultimedia, QtNetwork, QtSql, QtXml, QtSvg, and many others. Each module has a specific purpose — for example, UI programming, graphics, database access, and so on. The classes within each module provide developers with powerful mechanisms that expand their capabilities while simplifying application development. At the top of the module hierarchy sits QtCore, which enables console (non-GUI) applications. A QCoreApplication object must be created exactly once per application.

For applications with a graphical user interface, either the QtWidgets or QtQuick module is required. The QGuiApplication and QApplication classes are the backbone of Qt GUI applications. An instance of one of these classes must not be created more than once per application. Qt also offers additional optional modules that can be installed at the developer’s discretion.


Unlock the full potential of this chapter! Access the supplementary materials prepared for it, ask a question, share your experience, or join the discussion at: https://qt-book.com/01-69-en/

Leave a Reply

Your email address will not be published. Required fields are marked *