Qt5 Signals And Slots New Syntax

3/31/2022by admin
Qt5 Signals And Slots New Syntax 4,9/5 282 votes

Also, while Qt5 maintains backwards-compatibility with Qt4 -style Signals and Slots, that are based on macros, this project makes use of the newer Qt5 semantics, that are based on function pointers, for the sake of favouring new features over old. I can say that on my Debian 9 / Stretch computer, the example works.

  • Qt/C Tutorial 078. Do not mix the old syntax of signals and slots on SIGNAL SLOT macros with new syntax on pointers; Qt/C - Tutorial 076. Visualizing Mathematical Formulas on Qt; Qt/C - Tutorial 075. Improving the syntax of signals and slots in Qt 5.7 and above for overloaded signals and slots; QML - Tutorial 034.
  • QObject::connect( a, staticcast(&MyObject::signal), b, staticcast(&MyObject::slot)); //.so starting in Qt 5.7 we can use qOverload and friends: // this requires C14 enabled: QObject::connect( a, qOverload(&MyObject::signal), b, qOverload(&MyObject::slot)); // this is slightly longer, but works in C11: QObject::connect( a, QOverload::of(&MyObject::signal), b, QOverload::of(&MyObject::slot)); // there are also.
  • The new syntax, on the other hand, still requires MOC for signals to work, but not for slots. If a class only has slots and no signals, it need not have the QOBJECT macro and hence may not invoke the MOC, which not only reduces the final binary size but also reduces compilation time (no MOC call and no subsequent compiler call for the.

From Qt 5.0 onwards, Qt offers two different ways to write signal-slot connections in C++: The string-based connection syntax and the functor-based connection syntax. There are pros and cons to both syntaxes. The table below summarizes their differences.

String-basedFunctor-based
Type checking is done at...Run-timeCompile-time
Can perform implicit type conversionsY
Can connect signals to lambda expressionsY
Can connect signals to slots which have more arguments than the signal (using default parameters)Y
Can connect C++ functions to QML functionsY

The following sections explain these differences in detail and demonstrate how to use the features unique to each connection syntax.

Type Checking and Implicit Type Conversions

String-based connections type-check by comparing strings at run-time. There are three limitations with this approach:

  1. Connection errors can only be detected after the program has started running.
  2. Implicit conversions cannot be done between signals and slots.
  3. Typedefs and namespaces cannot be resolved.

Limitations 2 and 3 exist because the string comparator does not have access to C++ type information, so it relies on exact string matching.

In contrast, functor-based connections are checked by the compiler. The compiler catches errors at compile-time, enables implicit conversions between compatible types, and recognizes different names of the same type.

For example, only the functor-based syntax can be used to connect a signal that carries an int to a slot that accepts a double. A QSlider holds an int value while a QDoubleSpinBox holds a double value. The following snippet shows how to keep them in sync:

The following example illustrates the lack of name resolution. QAudioInput::stateChanged() is declared with an argument of type 'QAudio::State'. Thus, string-based connections must also specify 'QAudio::State', even if 'State' is already visible. This issue does not apply to functor-based connections because argument types are not part of the connection.

Making Connections to Lambda Expressions

The functor-based connection syntax can connect signals to C++11 lambda expressions, which are effectively inline slots. This feature is not available with the string-based syntax.

In the following example, the TextSender class emits a textCompleted() signal which carries a QString parameter. Here is the class declaration:

Here is the connection which emits TextSender::textCompleted() when the user clicks the button:

In this example, the lambda function made the connection simple even though QPushButton::clicked() and TextSender::textCompleted() have incompatible parameters. In contrast, a string-based implementation would require extra boilerplate code.

Note: The functor-based connection syntax accepts pointers to all functions, including standalone functions and regular member functions. However, for the sake of readability, signals should only be connected to slots, lambda expressions, and other signals.

Connecting C++ Objects to QML Objects

The string-based syntax can connect C++ objects to QML objects, but the functor-based syntax cannot. This is because QML types are resolved at run-time, so they are not available to the C++ compiler.

Qt5 Signals And Slots New Syntax

In the following example, clicking on the QML object makes the C++ object print a message, and vice-versa. Here is the QML type (in QmlGui.qml):

Here is the C++ class:

Here is the code that makes the signal-slot connections:

Note: All JavaScript functions in QML take parameters of var type, which maps to the QVariant type in C++.

When the QPushButton is clicked, the console prints, 'QML received: 'Hello from C++!'. Likewise, when the Rectangle is clicked, the console prints, 'C++ received: 'Hello from QML!'.

See Interacting with QML Objects from C++ for other ways to let C++ objects interact with QML objects.

Using Default Parameters in Slots to Connect to Signals with Fewer Parameters

Usually, a connection can only be made if the slot has the same number of arguments as the signal (or less), and if all the argument types are compatible.

The string-based connection syntax provides a workaround for this rule: If the slot has default parameters, those parameters can be omitted from the signal. When the signal is emitted with fewer arguments than the slot, Qt runs the slot using default parameter values.

Functor-based connections do not support this feature.

Suppose there is a class called DemoWidget with a slot printNumber() that has a default argument:

Using a string-based connection, DemoWidget::printNumber() can be connected to QApplication::aboutToQuit(), even though the latter has no arguments. The functor-based connection will produce a compile-time error:

To work around this limitation with the functor-based syntax, connect the signal to a lambda function that calls the slot. See the section above, Making Connections to Lambda Expressions.

Selecting Overloaded Signals and Slots

With the string-based syntax, parameter types are explicitly specified. As a result, the desired instance of an overloaded signal or slot is unambiguous.

In contrast, with the functor-based syntax, an overloaded signal or slot must be casted to tell the compiler which instance to use.

For example, QLCDNumber has three versions of the display() slot:

  1. QLCDNumber::display(int)
  2. QLCDNumber::display(double)
  3. QLCDNumber::display(QString)

To connect the int version to QSlider::valueChanged(), the two syntaxes are:

See also qOverload().

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

In case the reader is an aspiring programmer, but yet a hobbyist, one of the facts which he or she will already know is that, in order to design applications which have a Graphical User Interface, some predefined GUI Library is commonly used, and one example of a GUI Library which can be used is Qt 5. Therefore, in order to become proficient at using this library, like me, the reader might want a working example of:

  • Signals and Slots – The way in which Qt connects user-actions on the GUI, to actions which should be triggered from the actual program,
  • The use of the ‘QLabel’ class to display an image instead of more-common text,
  • The design of a very basic command-menu and a keyboard shortcut,
  • A QRC Resource Script.

Even though this example was created with ‘Qt Creator’ and Qt version 5.7, one of the main features of Qt Creator, its GUI Layout Designer, has been cut from the project, so that the means by which such mechanisms can be set up entirely via code, can be explored better. Also, while Qt5 maintains backwards-compatibility with Qt4 -style Signals and Slots, that are based on macros, this project makes use of the newer Qt5 semantics, that are based on function pointers, for the sake of favouring new features over old.

I can say that on my Debian 9 / Stretch computer, the example works. However, the Qt Library is designed to be cross-platform, and so the example should also work under Windows. What some people have suggested is that, in order to get such code to work under OS/X, ‘ccmake’ should be used with the ‘Unix Makefiles’ generator. This will assume that ‘XCode’ is already installed. (:1)

The Link where the compressed files, containing only source code, can be found (along some other compressed files that also contain precompiled binaries, belonging to other projects) is here:

In that Gopher-Hole, the files of interest would be ‘Creator_Test2.tar.gz‘ or ‘Creator_Test2.zip‘.

(Updated 8/16/2020, 11h40… )

1:)

I should elaborate on what the system requirements really are, to compile this exercise – which I at first undertook for my own education.

It would not be good enough, just to have a few Qt5 Libraries installed on a Windows computer. The reason for this is the fact that some of the features which Qt offers – Signals and Slots, specifically – are not just a question of applying C++. Instead, these features are advertised by the developers of Qt, as extensions to the C++ language. What this means is, that a preprocessor needs to run on some of the source files, that is referred to as the Meta-Object Compiler, or, the ‘MOC’. Additionally, something which is referred to as ‘RCC’ needs to be invoked, which parses the Resource Script, so that the resources identified within get compiled-in to the executable. This is similar to how Microsoft works with its RC-Files, only, a completely different language.

Qt5 Signals And Slots New Syntax

There is a certain way to install the Qt compiler under Linux, but then, a completely different way to install that under Windows. The Windows / Qt SDK can be downloaded from here:

The site I linked to above, also mentions that Qt can be installed on a Mac.

The CMake Script that I included, works on the assumption that some version of CMake is also installed on the target computer.

In theory, it might be possible for the C++ compiler to be MSVC (under Windows), but not the other two parsers which I just named above.

Slots

(Update 8/17/2020, 19h05: )

One of the observations which I’ve made about my own, first version of this program, is, that its Menu-Bar is rather lame. It seems to be superposed with the image that the main window displays, and while this might strike some people as cool, it might leave some people unimpressed. However, such details are easy to change. There is nothing that prevents that menu-bar from being re-attached to a different layout manager. By default, it would be attached to the main application window’s layout manager. But, by playing around with other layout managers, such as ‘QVBoxLayout’, widgets can be added to form a ‘vertical stack arrangement’, and then, simply to add the menu-bar to that layout manager, causes the menu automatically to be reparented.

Mind you, the initial problem of the superposition can also be solved, just by increasing the height of the window, to be 50 pixels greater than the size of its (centred) image, where before, it was only 20 pixels higher.

This modified version of the application, with the menu-bar at the bottom, can be found in the compressed files ‘Creator_Test4.tar.gz‘ and ‘Creator_Test4.zip‘.

Qt5 Signals And Slots New Syntax Analyzer

Enjoy,

Qt5 Signals And Slots New Syntax Example

Dirk

Comments are closed.