If you click through to the QWidget signal documentation you can see a.windowTitleChanged signal implemented here. Next we'll demonstrate that signal within our application. Qt 5 Documentation — Widget Signals. The code below gives a few examples of using the windowTitleChanged signal. Connecting in Qt 5. There are several ways to connect a signal in Qt 5. Qt 5 continues to support the old string-based syntax for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget).
Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals and slots are made possible by Qt's meta-object system .
Introduction
In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For example, if a user clicks a Close button, we probably want the window's close() function to be called.
Other toolkits achieve this kind of communication using callbacks. A callback is a pointer to a function, so if you want a processing function to notify you about some event you pass a pointer to another function (the callback) to the processing function. The processing function then calls the callback when appropriate. While successful frameworks using this method do exist, callbacks can be unintuitive and may suffer from problems in ensuring the type-correctness of callback arguments.
Signals and Slots
In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal. Qt's widgets have many pre-defined slots, but it is common practice to subclass widgets and add your own slots so that you can handle the signals that you are interested in.
- Signals and slots in Qt
The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Since the signatures are compatible, the compiler can help us detect type mismatches when using the function pointer-based syntax. The string-based SIGNAL and SLOT syntax will detect type mismatches at runtime. Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type. They are completely type safe.
All classes that inherit from QObject or one of its subclasses (e.g., QWidget ) can contain signals and slots. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. This is all the object does to communicate. It does not know or care whether anything is receiving the signals it emits. This is true information encapsulation, and ensures that the object can be used as a software component.
Slots can be used for receiving signals, but they are also normal member functions. Just as an object does not know if anything receives its signals, a slot does not know if it has any signals connected to it. This ensures that truly independent components can be created with Qt.
You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)
Together, signals and slots make up a powerful component programming mechanism.
Signals
Qt Signal Slot Example
Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.
When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following the
emit
statement will occur once all slots have returned. The situation is slightly different when using queued connections ; in such a case, the code following the emit
keyword will continue immediately, and the slots will be executed later. If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.
Signals are automatically generated by the moc and must not be implemented in the
.cpp
file. They can never have return types (i.e. use void
). A note about arguments: Our experience shows that signals and slots are more reusable if they do not use special types. If QScrollBar::valueChanged () were to use a special type such as the hypothetical QScrollBar::Range, it could only be connected to slots designed specifically for QScrollBar . Connecting different input widgets together would be impossible.
Slots
A slot is called when a signal connected to it is emitted. Slots are normal C++ functions and can be called normally; their only special feature is that signals can be connected to them.
Since slots are normal member functions, they follow the normal C++ rules when called directly. However, as slots, they can be invoked by any component, regardless of its access level, via a signal-slot connection. This means that a signal emitted from an instance of an arbitrary class can cause a private slot to be invoked in an instance of an unrelated class.
You can also define slots to be virtual, which we have found quite useful in practice.
Compared to callbacks, signals and slots are slightly slower because of the increased flexibility they provide, although the difference for real applications is insignificant. In general, emitting a signal that is connected to some slots, is approximately ten times slower than calling the receivers directly, with non-virtual function calls. This is the overhead required to locate the connection object, to safely iterate over all connections (i.e. checking that subsequent receivers have not been destroyed during the emission), and to marshall any parameters in a generic fashion. While ten non-virtual function calls may sound like a lot, it's much less overhead than any
new
or delete
operation, for example. As soon as you perform a string, vector or list operation that behind the scene requires new
or delete
, the signals and slots overhead is only responsible for a very small proportion of the complete function call costs. The same is true whenever you do a system call in a slot; or indirectly call more than ten functions. The simplicity and flexibility of the signals and slots mechanism is well worth the overhead, which your users won't even notice. Note that other libraries that define variables called
signals
or slots
may cause compiler warnings and errors when compiled alongside a Qt-based application. To solve this problem, #undef
the offending preprocessor symbol. Connecting the signal to the slot
Prior to the fifth version of Qt to connect the signal to the slot through the recorded macros, whereas in the fifth version of the recording has been applied, based on the signs.
Writing with macros:
Writing on the basis of indicators:
The advantage of the second option is that it is possible to determine the mismatch of signatures and the wrong slot or signal name of another project compilation stage, not in the process of testing applications.
An example of using signals and slots
For example, the use of signals and slots project was created, which in the main window contains three buttons, each of which is connected to the slot and these slots already transmit a signal in a single slot with the pressed button number.
Project Structure
- Project Structure
According to the tradition of conducting lessons enclosing structure of the project, which is absolutely trivial and defaulted to the disgrace that will not even describe members of her classes and files.
mainwindow.h
Thus, the following three buttons - three slots, one signal at all three buttons, which is fed into the slot button and transmits the number buttons into a single slot that displays a message with the number buttons.
mainwindow.cpp
A file in this logic is configured as described in the preceding paragraphs. Just check the code and go to the video page, there is shown in detail the whole process, demonstrated the application, and also shows what happens if we make coding a variety of errors.
Video
The one thing that confuses the most people in the beginning is the Signal & Slot mechanism of Qt. But it’s actually not that difficult to understand. In general Signals & Slots are used to loosely connect classes. Illustrated by the keyword
emit
, Signals are used to broadcast a message to all connected Slots. If no Slots are connected, the message 'is lost in the wild'. So a connection between Signals & Slots is like a TCP/IP connection with a few exceptions, but this metaphor will help you to get the principle. A Signal is an outgoing port and a Slot is an input only port and a Signal can be connected to multiple Slots.For me one of the best thins is, that you don’t have to bother with synchronization with different threads. For example you have one
QObject
that’s emitting the Signal and one QObject
receiving the Signal via a Slot, but in a different thread. You connect them via QObject::connect(...)
and the framework will deal with the synchronization for you. But there is one thing to keep in mind, if you have an object that uses implicitly sharing (like OpenCV’s cv::Mat) as parameter, you have to deal with the synchronization yourself.The standard use-case of Signals & Slots is interacting with the UI from the code while remaining responsive. This is nothing more than a specific version of 'communicating between threads'.Another benefit of using them is loosely coupled objects. The QObject
emitting the Signal does not know the Slot-QObject
and vice versa. This way you are able to connect QObjects
that are otherwise only reachable via a full stack of pointer-calls (eg. this->objA->...->objZ->objB->recieveAQString()
). Alone this can save you hours of work if someone decides to change some structure, eg. the UI.Qt5 Signal Slot Examples
Right now I only mentioned Signal- & Slot-methods. But you are not limited to methods - at least on the Slots side. You can use lambda functions and function pointers here. This moves some of the convenience from languages like Python or Swift to C++.
For some demonstrations I will use the following classes:
Using Connections
To connect a Signal to a Slot you can simply call
QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString)
or QObject::connect(a, SIGNAL(signalSometing(QString), b, SLOT(recieveAQString(QString))
if you want to use the 'old' syntax. The main difference is, if you use the new syntax, you have compile-time type-checking and -converting. But one big advantage of the 'old' method is that you don’t need to bother with inheritance and select the most specialized method.Lambdas can be a very efficient way of using Signals & Slots. If you just want to print the value, e.g. if the corresponding property changes, the most efficient way is to use lambdas. So by using lambdas you don’t have to blow up your classes with simple methods. But be aware, that if you manipulate any object inside the lambda you have to keep in mind, that synchronization issues (in a multithreaded environment) might occur.You will get an idea of how to use the different methods in the following example:
As you see,
recived a QString: 'Hello'
is printed two times. This happens because we connected the same Signals & Slots two times (using different methods). In the case, you don’t want that, you see some methods to prohibit that and other options in the next section Connection Types.One side note: if you are using
Qt::QueuedConnection
and your program looks like the following example, at some point you will probably wonder, why calling the Signal will not call the Slots until app.exec()
is called. The reason for this behavior is that the event queue, the Slot-call is enqueued, will start with this call (and block until program exits).And before we start with the next section here is a little trick to call a method of another thread inside the context of the other thread. This means, that the method will be executed by the other thread and not by the 'calling' one.
Qt Signal Slot Example C
To learn more about that here is your source of truth: https://doc.qt.io/qt-5/qmetamethod.html#invoke
Connection Types
Qt::AutoConnection
Qt::AutoConnection
is the default value for any QObject::connect(...)
call. If both QObjects that are about to be connected are in the same thread, a Qt::DirectConnection
is used. But if one is in another thread, a Qt::QueuedConnection
is used instead to ensure thread-safety. Please keep in mind, if you have both QObjects
in the same thread and connected them the connection type is Qt::DirectConnection
, even if you move one QObject
to another thread afterwards. I generally use Qt::QueuedConnection
explicitly if I know that the QObjects
are in different threads.Qt::DirectConnection
A
Qt::DirectConnection
is the connection with the most minimal overhead you can get with Signals & Slots. You can visualize it that way: If you call the Signal the method generated by Qt for you calls all Slots in place and then returns.Qt::QueuedConnection
The
Qt::QueuedConnection
will ensure that the Slot is called in the thread of the corresponding QObject
. It uses the fact, that every thread in Qt (QThread
) has a Event-queue by default. So if you call the Signal of the QObject
the method generated by Qt will enqueue the command to call the Slot in the Event-queue of the other QObjects
thread. The Signal-method returns immediately after enqueuing the command. To ensure all parameters exist within the other threads scope, they have to be copied. The meta-object system of Qt has to know all of the parameter types to be capable of that (see qRegisterMetaType).Qt::BlockingQueuedConnection
A
Qt::BlockingQueuedConnection
is like a Qt::QueuedConnection
but the Signal-method will block until the Slot returns. If you use this connection type on QObjects
that are in the same thread you will have a deadlock. And no one likes deadlocks (at least I don’t know anyone).Qt::UniqueConnection
Qt::UniqueConnection
is not really a connection type but a modifier. If you use this flag you are not able to connect the same connection again. But if you try it QObject::connect(...)
will fail and return false
.This is not everything you will ever need to know about Signals & Slots but with this information you can cover about 80% of all use-cases (in my opinion).If it happens and you need the other 20% of information, I’ll give you some good links to search your specific problem on:
The Qt documentation:
Very deep understanding:
Part1: https://woboq.com/blog/how-qt-signals-slots-work.html
Part2: https://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html
Part3: https://woboq.com/blog/how-qt-signals-slots-work-part3-queuedconnection.html
< previous step | index | next step >