2016-12-07 Programming Qt Tutorials Niclas Roßberger
The one thing that confuses the most people in the beginning is theSignal & Slot mechanism of Qt. But it’s actually not that difficult tounderstand. In general Signals & Slots are used to loosely connectclasses. Illustrated by the keyword emit
, Signals are used tobroadcast 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 thismetaphor will help you to get the principle. A Signal is an outgoingport and a Slot is an input only port and a Signal can be connected tomultiple Slots.
For me one of the best thins is, that you don’t have to bother withsynchronization with different threads. For example, you have oneQObject
that’s emitting the Signal and one QObject
receiving theSignal via a Slot, but in a different thread. You connect them viaQObject::connect(...)
and the framework will deal with thesynchronization for you. But there is one thing to keep in mind, if youhave an object that uses implicitly sharing (like OpenCV’s cv::Mat) asparameter, you have to deal with the synchronization yourself. Thestandard use-case of Signals & Slots is interacting with the UI from thecode while remaining responsive. This is nothing more than a specificversion of “communicating between threads”. Another benefit of usingthem is loosely coupled objects. The QObject
emitting the Signal doesnot know the Slot-QObject
and vice versa. This way you are able toconnect QObjects
that are otherwise only reachable via a full stack ofpointer-calls (e.g. this->objA->...->objZ->objB->recieveAQString()
).Alone this can save you hours of work if someone decides to change somestructure, e.g. the UI.
Right now I only mentioned Signal- & Slot-methods. But you are notlimited to methods - at least on the Slots side. You can use lambdafunctions and function pointers here. This moves some conveniencesfrom languages like Python or Swift to C++.
For some demonstrations I will use the following classes:
class AObject: public QObject{ Q_OBJECTpublic: AObject(){ }signals: void signalSometing(QString param);};class BObject: public QObject{ Q_OBJECTpublic: BObject(){ }public slots: void recieveAQString(QString param){ qDebug() << "recived a QString: " << param; }};
Using Connections
To connect a Signal to a Slot you can simply callQObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString)
orQObject::connect(a, SIGNAL(signalSometing(QString), b, SLOT(recieveAQString(QString))
if you want to use the “old” syntax. The main difference is, if you usethe new syntax, you have compile-time type-checking and -converting. Butone big advantage of the “old” method is that you don’t need to botherwith inheritance and select the most specialized method. Lambdas can bea very efficient way of using Signals & Slots. If you just want to printthe value, e.g. if the corresponding property changes, the mostefficient way is to use lambdas. So by using lambdas you don’t have toblow up your classes with simple methods. But be aware, that if youmanipulate any object inside the lambda you have to keep in mind, thatsynchronization issues (in a multithreaded environment) might occur.
You will get an idea of how to use the different methods in thefollowing example:
auto a = new AObject;auto b = new BObject;QObject::connect(a, SIGNAL(signalSometing(QString)), b, SLOT(recieveAQString(QString))); // old MethodQObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString); // new MethodQObject::connect(a, &AObject::signalSometing, [&](const QString& msg){ qDebug() << "a message for a lambda: " << msg;}); // lambda Methoda->signalSometing("Hello");/* output:recived a QString: "Hello"recived a QString: "Hello"a message for a lambda: "Hello"*/
As you see, recived a QString: "Hello"
is printed two times. Thishappens because we connected the same Signals & Slots two times (usingdifferent methods). In the case, you don’t want that, you see somemethods to prohibit that and other options in the next sectionConnection Types.
One side note: if you are using Qt::QueuedConnection
and your programlooks like the following example, at some point you will probablywonder, why calling the Signal will not call the Slots untilapp.exec()
is called. The reason for this behavior is that the eventqueue, the Slot-call is enqueued, will start with this call (and blockuntil program exits).
int main(int argc, char *argv[]){ QApplication app(argc, argv); auto a = new AObject; auto b = new BObject; QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, Qt::QueuedConnection); a->signalSometing("Hello"); // Nothing happens return app.exec(); // 'recived a QString: "Hello"' will be printed}
And before we start with the next section here is a little trick to calla method of another thread inside the context of the other thread. Thismeans, that the method will be executed by the other thread and not bythe “calling” one.
int methodIndex = b->metaObject()->indexOfMethod("recieveAQString(QString)");QMetaMethod method = b->metaObject()->method(methodIndex);method.invoke(b, Qt::QueuedConnection, Q_ARG(QString, "Hello"));
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 anyQObject::connect(...)
call. If both QObjects that are about to beconnected are in the same thread, a Qt::DirectConnection
is used. Butif one is in another thread, a Qt::QueuedConnection
is used instead toensure thread-safety. Please keep in mind, if you have both QObjects
in the same thread and connected them the connection type isQt::DirectConnection
, even if you move one QObject
to another threadafterwards. I generally use Qt::QueuedConnection
explicitly if I knowthat the QObjects
are in different threads.
Qt::DirectConnection
A Qt::DirectConnection
is the connection with the most minimaloverhead you can get with Signals & Slots. You can visualize it thatway: If you call the Signal the method generated by Qt for you calls allSlots in place and then returns.
Qt::QueuedConnection
The Qt::QueuedConnection
will ensure that the Slot is called in thethread of the corresponding QObject
. It uses the fact, that everythread in Qt (QThread
) has a Event-queue by default. So if you callthe Signal of the QObject
the method generated by Qt will enqueue thecommand to call the Slot in the Event-queue of the other QObjects
thread. The Signal-method returns immediately after enqueuing thecommand. 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 the parameter types to be capable of that (seeqRegisterMetaType).
Qt::BlockingQueuedConnection
A Qt::BlockingQueuedConnection
is like a Qt::QueuedConnection
butthe Signal-method will block until the Slot returns. If you use thisconnection type on QObjects
that are in the same thread you will havea 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 connectionagain. But if you try it QObject::connect(...)
will fail and returnfalse
.
// Each Example is executed individually// Example 1qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString)qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString)// prints:// true// true// Example 2qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection));qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection));// prints:// true// false// Example 3qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection));qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString)// prints:// true// true// Example 4qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString);qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection));// prints:// true// false// Example 5 (Different connection types)qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::DirectConnection | Qt::UniqueConnection));qDebug() <<QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString, static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));// prints:// true// false
This is not everything you will ever need to know about Signals & Slotsbut with this information you can cover about 80% of all use-cases (inmy 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:
https://doc.qt.io/qt-5/signalsandslots.html
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
Continue in this series:
- How to start with Qt?
- Writing a basic Qt project with Qt Creator
- Should I use Qt containers or the std ones?