Qt5 Virtual Slot

Posted on

While Qt 5.0 introduced a lot of new features, it was mostly compatible with Qt 4 and allowed developers to seamlessly migrate to the new major version. In 2014, Digia formed the Qt Company that is now responsible for Qt development, commercialization, and licensing. Note that the browser will automatically handle navigation to the location specified by link unless the openLinks property is set to false or you call setSource in a slot connected. This mechanism is used to override the default navigation features of the browser. virtual slot void QTextBrowser:: backward.

In this chapter, you will learn what Qt is and how it evolved. We will describe the structure of the Qt framework and the differences between its versions. Finally, you will learn how to decide which Qt licensing scheme is right for your projects.

The main topics covered in this chapter are:

  • Qt history
  • Supported platforms
  • Structure of the Qt framework
  • Qt versions
  • Qt licenses

The development of Qt started in 1991 by two Norwegians—Eirik Chambe-Eng and Haavard Nord—who were looking to create a cross-platform GUI programming toolkit. The first commercial client of Trolltech (the company that created the Qt toolkit) was the European Space Agency. The commercial use of Qt helped Trolltech sustain further development. At that time, Qt was available for two platforms—Unix/X11 and Windows—however, developing with Qt for Windows required buying a proprietary license, which was a significant drawback in porting the existing Unix/Qt applications.

A major step forward was the release of Qt Version 3.0 in 2001, which saw the initial support for Mac as well as an option to use Qt for Unix and Mac under a liberal GPL license. Still, Qt for Windows was only available under a paid license. Nevertheless, at that time, Qt had support for all the important players in the market—Windows, Mac, and Unix desktops, with Trolltech's mainstream product and Qt for embedded Linux.

In 2005, Qt 4.0 was released, which was a real breakthrough for a number of reasons. First, the Qt API was completely redesigned, which made it cleaner and more coherent. Unfortunately, at the same time, it made the existing Qt-based code incompatible with 4.0, and many applications needed to be rewritten from scratch or required much effort to be adapted to the new API. It was a difficult decision, but from the time perspective, we can see it was worth it. Difficulties caused by changes in the API were well countered by the fact that Qt for Windows was finally released under GPL. Many optimizations were introduced that made Qt significantly faster. Lastly, Qt, which was a single library until now, was divided into a number of modules. This allowed programmers to only link to the functionality that they used in their applications, reducing the memory footprint and the dependencies of their software.

In 2008, Trolltech was sold to Nokia, which at that time was looking for a software framework to help it expand and replace its Symbian platform in the future. The Qt community became divided; some people were thrilled, others were worried after seeing Qt's development get transferred to Nokia. Either way, new funds were pumped into Qt, speeding up its progress and opening it for mobile platforms—Symbian and then Maemo and MeeGo.

For Nokia, Qt was not considered a product of its own, but rather a tool. Therefore, Nokia decided to introduce Qt to more developers by adding a very liberal Lesser General Public License (LGPL) that allowed the usage of the framework for both open and closed source development.

Bringing Qt to new platforms and less powerful hardware required a new approach to create user interfaces and to make them more lightweight, fluid, and attractive. Nokia engineers working on Qt came up with a new declarative language to develop such interfaces—the Qt Modeling Language (QML) and a Qt runtime for it called Qt Quick.

The latter became the primary focus of the further development of Qt, practically stalling all non-mobile-related work, channeling all efforts to make Qt Quick faster, easier, and more widespread. Qt 4 was already in the market for seven years, and it became obvious that another major version of Qt had to be released. It was decided to bring more engineers to Qt by allowing anyone to contribute to the project. The Qt Project founded by Nokia in 2011 provided an infrastructure for code review and introduced an open governance model, allowing outside developers to participate in decision making.

Nokia did not manage to finish working on Qt 5.0. As a result of an unexpected turnover of Nokia toward different technology in 2011, the Qt division was sold in mid 2012 to the Finnish company Digia that managed to complete the effort and release Qt 5.0, a completely restructured framework, in December of the same year. While Qt 5.0 introduced a lot of new features, it was mostly compatible with Qt 4 and allowed developers to seamlessly migrate to the new major version.

In 2014, Digia formed the Qt Company that is now responsible for Qt development, commercialization, and licensing. All Qt-related web resources scattered across Qt Project and Digia websites were eventually unified at https://www.qt.io/. Qt continues to receive bug fixes, new features, and new platform support. This book is based on Qt 5.9, which was released in 2017.

Qt is an application-programming framework that is used to develop cross-platform applications. What this means is that software written for one platform can be ported and executed on another platform with little or no effort. This is obtained by limiting the application source code to a set of calls to routines and libraries available to all the supported platforms, and by delegating all tasks that may differ between platforms (such as drawing on the screen and accessing system data or hardware) to Qt. This effectively creates a layered environment (as shown in the following diagram), where Qt hides all platform-dependent aspects from the application code:

Of course, at times, we need to use some functionality that Qt doesn't provide. In such situations, it is important to use a conditional compilation for platform-specific code. Qt provides a wide set of macros specifying the current platform. We will return to this topic in Chapter 6, Qt Core Essentials.

The framework is available for a number of platforms, ranging from classical desktop environments through embedded systems to mobile devices. Qt 5.9 supports the following platforms:Â

  • Desktop platforms: Windows, Linux, and macOS
  • Mobile platforms: UWP, Android, and iOS
  • Embedded platforms: VxWorks, INTEGRITY, QNX, and Embedded Linux
Slot

It is likely that the list of supported platforms will change in future Qt versions. You should refer to the Supported Platforms documentation page for your Qt version for detailed information about supported versions of operating systems and compilers.

For the most part of the history of desktop application development, specifying sizes of GUI elements in pixels was the common practice. While most operating systems had dots per inch (DPI) settings and APIs for taking it into account for a long time, the majority of existing displays had approximately the same DPI, so applications without high DPI support were common.

The situation changed when high-DPI displays became more common in the market—most notably in mobile phones and tablets, but also in laptops and desktops. Now, even if you only target desktop platforms, you should think about supporting different DPI settings. When you target mobile devices, this becomes mandatory.

If you are using Qt Widgets or Qt Quick, you often don't need to specify pixel sizes at all. Standard widgets and controls will use fonts, margins, and offsets defined by the style. If layouts are used, Qt will determine positions and sizes of all GUI items automatically. Avoid specifying constant sizes for GUI elements when possible. You may use sizes related to sizes of other GUI elements, the window, or the screen. Qt also provides an API for querying screen DPI, GUI style metrics, and font metrics, which should help to determine the optimal size for the current device.

On macOS and iOS, Qt Widgets and Qt Quick applications are scaled automatically using a virtual coordinate system. Pixel values in the application remain the same, but the GUI will scale according to the DPI of the current display. For example, if the pixel ratio is set to 2 (a common value for retina displays), creating a widget with 100 'pixels' width will produce a widget with 200 physical pixels. That means that the application doesn't have to be highly aware of DPI variations. However, this scaling does not apply to OpenGL, which always uses physical pixels.

Each Qt version number (for example, 5.9.2) consists of major, minor, and patch components. Qt pays special attention to forwards and backwards compatibility between different versions. Small changes which are both forwards and backwards compatible (typically bug fixes without changing any API) are indicated by changing only the patch version. New minor versions usually bring in new API and features, so they are not forwards compatible. However, all minor versions are backwards binary and source compatible. This means that if you're transitioning to a newer minor version (for example, from 5.8 to 5.9), you should always be able to rebuild your project without changes. You can even transition to a new minor version without rebuilding, by only updating shared Qt libraries (or letting the package manager of the OS do that). Major releases indicate big changes and may break backwards compatibility. However, the latest major release (5.0) was mostly source compatible with the previous version.

Qt declares Long Term Support (LTS) for certain versions. LTS versions receive patch-level releases with bug fixes and security fixes for three years. Commercial support is available for even longer periods. Current LTS releases at the time of writing are 5.6 and 5.9.

As Qt expanded over time, its structure evolved. At first, it was just a single library, then a set of libraries. When it became harder to maintain and update for the growing number of platforms that it supported, a decision was made to split the framework into much smaller modules contained in two module groups—Qt Essentials and Qt Add-ons. A major decision relating to the split was that each module could now have its own independent release schedule.

The Essentials group contains modules that are mandatory to implement for every supported platform. This implies that if you are implementing your system using modules from this group only, you can be sure that it can be easily ported to any other platform that Qt supports. The most important relations between Qt Essentials modules are shown in the following diagram:

Some of the modules are explained as follows:

  • The Qt Core module contains the most basic Qt functionality that all other modules rely on. It provides support for event processing, meta-objects, data I/O, text processing, and threading. It also brings a number of frameworks, such as the Animation framework, the State Machine framework, and the Plugin framework.
  • The Qt GUI module provides basic cross-platform support to build user interfaces. It contains the common functionality required by more high-level GUI modules (Qt Widgets and Qt Quick). Qt GUI contains classes that are used to manipulate windows that can be rendered using either the raster engine or OpenGL. Qt supports desktop OpenGL as well as OpenGL ES 1.1 and 2.0.
  • Qt Widgets extends the GUI module with the ability to create a user interface using widgets, such as buttons, edit boxes, labels, data views, dialog boxes, menus, and toolbars, which are arranged using a special layout engine. Qt Widgets utilizes Qt's event system to handle input events in a cross-platform way. This module also contains the implementation of an object-oriented 2D graphics canvas called Graphics View.
  • Qt Quick is an extension of Qt GUI, which provides a means to create lightweight fluid user interfaces using QML. It is described in more detail later in this chapter, as well as in Chapter 11, Introduction to Qt Quick.
  • Qt QML is an implementation of the QML language used in Qt Quick. It also provides API to integrate custom C++ types into QML's JavaScript engine and to integrate QML code with C++.
  • Qt Network brings support for IPv4 and IPv6 networking using TCP and UDP. It also contains HTTP, HTTPS, FTP clients, and it extends support for DNS lookups.
  • Qt Multimedia allows programmers to access audio and video hardware (including cameras and FM radio) to record and play multimedia content. It also features 3D positional audio support.
  • Qt SQL brings a framework that is used to manipulate SQL databases in an abstract way.

Note

There are also other modules in this group, but we will not focus on them in this book. If you want to learn more about them, you can look them up in the Qt reference manual.

This group contains modules that are optional for any platform. This means that if a particular functionality is not available on some platform or there is nobody willing to spend time working on this functionality for a platform, it will not prevent Qt from supporting this platform. We'll mention some of the most important modules here:

  • Qt Concurrent: This handles multi-threaded processing
  • Qt 3D: This provides high-level OpenGL building blocks
  • Qt Gamepad: This enables applications to support gamepad hardware
  • Qt D-Bus: This allows your application to communicate with others via the D-Bus mechanism
  • Qt XML Patterns: This helps us to access XML data

Many other modules are also available, but we will not cover them here.

Some Qt features require additional build steps during the compilation and linking of the project. For example, Meta-Object Compiler (moc), User Interface Compiler (uic), and Resource Compiler (rcc) may need to be executed to handle Qt's C++ extensions and features. For convenience, Qt provides the qmake executable that manages your Qt project and generates files required for building it on the current platform (such as Makefile for the make utility). qmake reads the project's configuration from a project file with the .pro extension. Qt Creator (the IDE that comes with Qt) automatically creates and updates that file, but it can be edited manually to alter the build process.

Alternatively, CMake can be used to organize and build the project. Qt provides CMake plugins for performing all the necessary build actions. Qt Creator also has fairly good support for CMake projects. CMake is more advanced and powerful than qmake, but it's probably not needed for projects with a simple build process.

You can use modern C++ in your Qt projects. Qt's build tool (qmake) allows you to specify the C++ standard you want to target. Qt itself introduces an improved and extended API by using new C++ features when possible. For example, it uses ref-qualified member functions and introduces methods accepting initializer lists and rvalue references. It also introduces new macros that help you deal with compilers that may or may not support new standards.Â

If you use a recent C++ revision, you have to pay attention to the compiler versions you use across the target platforms because older compilers may not support the new standard. In this book, we will assume C++11 support, as it is widely available already. Thus, we'll use C++11 features in our code, such as range-based for loops, scoped enumerations, and lambda expressions.Â

Qt is available under two different licensing schemes—you can choose between a commercial license and an open source one. We will discuss both here to make it easier for you to choose. If you have any doubts regarding whether a particular licensing scheme applies to your use case, you better consult a professional lawyer.

The advantage of open source licenses is that we don't have to pay anyone to use Qt; however, the downside is that there are some limitations imposed on how it can be used.

When choosing the open source edition, we have to choose between GPL 3.0 and LGPL 3. Since LGPL is more liberal, in this chapter we will focus on it. Choosing LGPL allows you to use Qt to implement systems that are either open source or closed source—you don't have to reveal the sources of your application to anyone if you don't want to.

However, there are a number of restrictions you need to be aware of:

  • Any modifications that you make to Qt itself need to be made public, for example, by distributing source code patches alongside your application binary.
  • LGPL requires that users of your application must be able to replace Qt libraries that you provide them with other libraries with the same functionality (for example, a different version of Qt). This usually means that you have to dynamically link your application against Qt so that the user can simply replace Qt libraries with his own. You should be aware that such substitutions can decrease the security of your system; thus, if you need it to be very secure, open source may not be the option for you.
  • LGPL is incompatible with a number of licenses, especially proprietary ones, so it is possible that you won't be able to use Qt with some commercial components.

Some Qt modules may have different licensing restrictions. For example, Qt Charts, Qt Data Visualization, and Qt Virtual Keyboard modules are not available under LGPL and can only be used under GPL or the commercial license.

The open source edition of Qt can be downloaded directly from https://www.qt.io.

Qt5 Virtual Slots

Qt virtual slot

Most of the restrictions are lifted if you decide to buy a commercial license for Qt. This allows you to keep the entire source code a secret, including any changes you may want to incorporate into Qt. You can freely link your application statically against Qt, which means fewer dependencies, a smaller deployment bundle size, and a faster startup. It also increases the security of your application, as end users cannot inject their own code into the application by replacing a dynamically loaded library with their own.

In this chapter, you learned about the architecture of Qt. We saw how it evolved over time and we had a brief overview of what it looks like now. Qt is a complex framework and we will not manage to cover it all, as some parts of its functionality are more important for game programming than others that you can learn on your own in case you ever need them. Now that you know what Qt is, we can proceed with the next chapter, where you will learn how to install Qt on to your development machine.

This is the sequel of my previous article explaining the implementation details of the signals and slots.In the Part 1, we have seenthe general principle and how it works with the old syntax.In this blog post, we will see the implementation details behind thenew function pointerbased syntax in Qt5.

New Syntax in Qt5

The new syntax looks like this:

Why the new syntax?

I already explained the advantages of the new syntax in adedicated blog entry.To summarize, the new syntax allows compile-time checking of the signals and slots. It also allowsautomatic conversion of the arguments if they do not have the same types.As a bonus, it enables the support for lambda expressions.

New overloads

There was only a few changes required to make that possible.
The main idea is to have new overloads to QObject::connect which take the pointersto functions as arguments instead of char*

There are three new static overloads of QObject::connect: (not actual code)

The first one is the one that is much closer to the old syntax: you connect a signal from the senderto a slot in a receiver object.The two other overloads are connecting a signal to a static function or a functor object withouta receiver.

They are very similar and we will only analyze the first one in this article.

Pointer to Member Functions

Before continuing my explanation, I would like to open a parenthesis totalk a bit about pointers to member functions.

Here is a simple sample code that declares a pointer to member function and calls it.

Pointers to member and pointers to member functions are usually part of the subset of C++ that is not much used and thus lesser known.
The good news is that you still do not really need to know much about them to use Qt and its new syntax. All you need to remember is to put the & before the name of the signal in your connect call. But you will not need to cope with the ::*, .* or ->* cryptic operators.

These cryptic operators allow you to declare a pointer to a member or access it.The type of such pointers includes the return type, the class which owns the member, the types of each argumentand the const-ness of the function.

You cannot really convert pointer to member functions to anything and in particular not tovoid* because they have a different sizeof.
If the function varies slightly in signature, you cannot convert from one to the other.For example, even converting from void (MyClass::*)(int) const tovoid (MyClass::*)(int) is not allowed.(You could do it with reinterpret_cast; but that would be an undefined behaviour if you callthem, according to the standard)

Pointer to member functions are not just like normal function pointers.A normal function pointer is just a normal pointer the address where thecode of that function lies.But pointer to member function need to store more information:member functions can be virtual and there is also an offset to apply to thehidden this in case of multiple inheritance.
sizeof of a pointer to a member function can evenvary depending of the class.This is why we need to take special care when manipulating them.

Type Traits: QtPrivate::FunctionPointer

Let me introduce you to the QtPrivate::FunctionPointer type trait.
A trait is basically a helper class that gives meta data about a given type.Another example of trait in Qt isQTypeInfo.

What we will need to know in order to implement the new syntax is information about a function pointer.

The template<typename T> struct FunctionPointer will give us informationabout T via its member.

  • ArgumentCount: An integer representing the number of arguments of the function.
  • Object: Exists only for pointer to member function. It is a typedef to the class of which the function is a member.
  • Arguments: Represents the list of argument. It is a typedef to a meta-programming list.
  • call(T &function, QObject *receiver, void **args): A static function that will call the function, applying the given parameters.

Qt Virtual Slot

Qt still supports C++98 compiler which means we unfortunately cannot require support for variadic templates.Therefore we had to specialize our trait function for each number of arguments.We have four kinds of specializationd: normal function pointer, pointer to member function,pointer to const member function and functors.For each kind, we need to specialize for each number of arguments. We support up to six arguments.We also made a specialization using variadic templateso we support arbitrary number of arguments if the compiler supports variadic templates.

The implementation of FunctionPointer lies inqobjectdefs_impl.h.

QObject::connect

The implementation relies on a lot of template code. I am not going to explain all of it.

Here is the code of the first new overload fromqobject.h:

You notice in the function signature that sender and receiverare not just QObject* as the documentation points out. They are pointers totypename FunctionPointer::Object instead.This uses SFINAEto make this overload only enabled for pointers to member functionsbecause the Object only exists in FunctionPointer ifthe type is a pointer to member function.

We then start with a bunch ofQ_STATIC_ASSERT.They should generate sensible compilation error messages when the user made a mistake.If the user did something wrong, it is important that he/she sees an error hereand not in the soup of template code in the _impl.h files.We want to hide the underlying implementation from the user who should not needto care about it.
That means that if you ever you see a confusing error in the implementation details,it should be considered as a bug that should be reported.

We then allocate a QSlotObject that is going to be passed to connectImpl().The QSlotObject is a wrapper around the slot that will help calling it. It alsoknows the type of the signal arguments so it can do the proper type conversion.
We use List_Left to only pass the same number as argument as the slot, which allows connectinga signal with many arguments to a slot with less arguments.

QObject::connectImpl is the private internal functionthat will perform the connection.It is similar to the original syntax, the difference is that instead of storing amethod index in the QObjectPrivate::Connection structure,we store a pointer to the QSlotObjectBase.

The reason why we pass &slot as a void** is only tobe able to compare it if the type is Qt::UniqueConnection.

We also pass the &signal as a void**.It is a pointer to the member function pointer. (Yes, a pointer to the pointer)

Signal Index

We need to make a relationship between the signal pointer and the signal index.
We use MOC for that. Yes, that means this new syntaxis still using the MOC and that there are no plans to get rid of it :-).

MOC will generate code in qt_static_metacallthat compares the parameter and returns the right index.connectImpl will call the qt_static_metacall function with thepointer to the function pointer.

Once we have the signal index, we can proceed like in the other syntax.

The QSlotObjectBase

QSlotObjectBase is the object passed to connectImplthat represents the slot.

Before showing the real code, this is what QObject::QSlotObjectBasewas in Qt5 alpha:

It is basically an interface that is meant to be re-implemented bytemplate classes implementing the call and comparison of thefunction pointers.

It is re-implemented by one of the QSlotObject, QStaticSlotObject orQFunctorSlotObject template class.

Fake Virtual Table

The problem with that is that each instantiation of those object would need to create a virtual table which contains not only pointer to virtual functionsbut also lot of information we do not need such asRTTI.That would result in lot of superfluous data and relocation in the binaries.

In order to avoid that, QSlotObjectBase was changed not to be a C++ polymorphic class.Virtual functions are emulated by hand.

The m_impl is a (normal) function pointer which performsthe three operations that were previously virtual functions. The 're-implementations'set it to their own implementation in the constructor.

Please do not go in your code and replace all your virtual functions by such ahack because you read here it was good.This is only done in this case because almost every call to connectwould generate a new different type (since the QSlotObject has template parameterswich depend on signature of the signal and the slot).

Protected, Public, or Private Signals.

Signals were protected in Qt4 and before. It was a design choice as signals should be emittedby the object when its change its state. They should not be emitted fromoutside the object and calling a signal on another object is almost always a bad idea.

However, with the new syntax, you need to be able take the addressof the signal from the point you make the connection.The compiler would only let you do that if you have access to that signal.Writing &Counter::valueChanged would generate a compiler errorif the signal was not public.

In Qt 5 we had to change signals from protected to public.This is unfortunate since this mean anyone can emit the signals.We found no way around it. We tried a trick with the emit keyword. We tried returning a special value.But nothing worked.I believe that the advantages of the new syntax overcome the problem that signals are now public.

Sometimes it is even desirable to have the signal private. This is the case for example inQAbstractItemModel, where otherwise, developers tend to emit signalfrom the derived class which is not what the API wants.There used to be a pre-processor trick that made signals privatebut it broke the new connection syntax.
A new hack has been introduced.QPrivateSignal is a dummy (empty) struct declared private in the Q_OBJECTmacro. It can be used as the last parameter of the signal. Because it is private, only the objecthas the right to construct it for calling the signal.MOC will ignore the QPrivateSignal last argument while generating signature information.See qabstractitemmodel.h for an example.

More Template Code

The rest of the code is inqobjectdefs_impl.h andqobject_impl.h.It is mostly standard dull template code.

I will not go into much more details in this article,but I will just go over few items that are worth mentioning.

Meta-Programming List

As pointed out earlier, FunctionPointer::Arguments is a listof the arguments. The code needs to operate on that list:iterate over each element, take only a part of it or select a given item.

That is why there isQtPrivate::List that can represent a list of types. Some helpers to operate on it areQtPrivate::List_Select andQtPrivate::List_Left, which give the N-th element in the list and a sub-list containingthe N first elements.

The implementation of List is different for compilers that support variadic templates and compilers that do not.

With variadic templates, it is atemplate<typename... T> struct List;. The list of arguments is just encapsulatedin the template parameters.
For example: the type of a list containing the arguments (int, QString, QObject*) would simply be:

Without variadic template, it is a LISP-style list: template<typename Head, typename Tail > struct List;where Tail can be either another List or void for the end of the list.
The same example as before would be:

ApplyReturnValue Trick

In the function FunctionPointer::call, the args[0] is meant to receive the return value of the slot.If the signal returns a value, it is a pointer to an object of the return type ofthe signal, else, it is 0.If the slot returns a value, we need to copy it in arg[0]. If it returns void, we do nothing.

The problem is that it is not syntaxically correct to use thereturn value of a function that returns void.Should I have duplicated the already huge amount of code duplication: once for the voidreturn type and the other for the non-void?No, thanks to the comma operator.

In C++ you can do something like that:

You could have replaced the comma by a semicolon and everything would have been fine.

Where it becomes interesting is when you call it with something that is not void:

There, the comma will actually call an operator that you even can overload.It is what we do inqobjectdefs_impl.h

ApplyReturnValue is just a wrapper around a void*. Then it can be usedin each helper. This is for example the case of a functor without arguments:

This code is inlined, so it will not cost anything at run-time.

Conclusion

This is it for this blog post. There is still a lot to talk about(I have not even mentioned QueuedConnection or thread safety yet), but I hope you found thisinterresting and that you learned here something that might help you as a programmer.

Update:The part 3 is available.