Qt Creator Signals And Slots Tutorial



This blog is part of a series of blogs explaining the internals of signals and slots.

In this article, we will explore the mechanisms powering the Qt queued connections.

Most slot machines have special symbols that boost your chances to win. Wildcard symbols, symbols that give free spins or even symbols that start mini-games are a major fun factor and occur in most of the modern slot games. In this tutorial, we will make a pirate themed slot game similar to such games! I hope these articles have demystified signals and slots, and that knowing a bit how this works under the hood will help you make better use of them in your applications. Woboq is a software company that specializes in development and consulting around Qt and C.

Summary from Part 1

In the first part, we saw that signalsare just simple functions, whose body is generated by moc. They are just calling QMetaObject::activate, with an array of pointers to arguments on the stack.Here is the code of a signal, as generated by moc: (from part 1)

Connect Signals to Slots: Under the Edit menu, select 'Edit signals/slots'- You are now in Signal/Slots editing mode. Click and drag (and release) from Push Button 1 to somewhere on the main window's widget. A dialog box will appear asking you to configure signals and slots. On the left are signals emitted by a push button. Qt Designer is the Qt tool for designing and building graphical user interfaces (GUIs) with Qt Widgets.You can compose and customize your windows or dialogs in a what-you-see-is-what-you-get (WYSIWYG) manner, and test them using different styles and resolutions. Qt Designer's Signals and Slots Editing Mode In Qt Designer's signals and slots editing mode, you can connect objects in a form together using Qt's signals and slots mechanism. Both widgets and layouts can be connected via an intuitive connection interface, using the menu of compatible signals and slots provided by Qt Designer.

QMetaObject::activatewill then look in internal data structures to find out what are the slots connected to that signal.As seen in part 1, for each slot, the following code will be executed:

So in this blog post we will see what exactly happens in queued_activateand other parts that were skipped for the BlockingQueuedConnection

Qt Event Loop

A QueuedConnection will post an event to the event loop to eventually be handled.

When posting an event (in QCoreApplication::postEvent),the event will be pushed in a per-thread queue(QThreadData::postEventList).The event queued is protected by a mutex, so there is no race conditions when threadspush events to another thread's event queue.

Once the event has been added to the queue, and if the receiver is living in another thread,we notify the event dispatcher of that thread by calling QAbstractEventDispatcher::wakeUp.This will wake up the dispatcher if it was sleeping while waiting for more events.If the receiver is in the same thread, the event will be processed later, as the event loop iterates.

The event will be deleted right after being processed in the thread that processes it.

An event posted using a QueuedConnection is a QMetaCallEvent. When processed, that event will call the slot the same way we call them for direct connections.All the information (slot to call, parameter values, ...) are stored inside the event.

Copying the parameters

The argv coming from the signal is an array of pointers to the arguments. The problem is that these pointers point to the stack of the signal where the arguments are. Once the signal returns, they will not be valid anymore. So we'll have to copy the parameter values of the function on the heap. In order to do that, we just ask QMetaType. We have seen in the QMetaType article that QMetaType::create has the ability to copy any type knowing it's QMetaType ID and a pointer to the type.

To know the QMetaType ID of a particular parameter, we will look in the QMetaObject, which contains the name of all the types. We will then be able to look up the particular type in the QMetaType database.

queued_activate

We can now put it all together and read through the code ofqueued_activate, which is called by QMetaObject::activate to prepare a Qt::QueuedConnection slot call.The code showed here has been slightly simplified and commented:

Upon reception of this event, QObject::event will set the sender and call QMetaCallEvent::placeMetaCall. That later function will dispatch just the same way asQMetaObject::activate would do it for direct connections, as seen in Part 1

BlockingQueuedConnection

BlockingQueuedConnection is a mix between DirectConnection and QueuedConnection. Like with aDirectConnection, the arguments can stay on the stack since the stack is on the thread thatis blocked. No need to copy the arguments.Like with a QueuedConnection, an event is posted to the other thread's event loop. The event also containsa pointer to a QSemaphore. The thread that delivers the event will release thesemaphore right after the slot has been called. Meanwhile, the thread that called the signal will acquirethe semaphore in order to wait until the event is processed.

It is the destructor of QMetaCallEvent which will release the semaphore. This is good becausethe event will be deleted right after it is delivered (i.e. the slot has been called) but also whenthe event is not delivered (e.g. because the receiving object was deleted).

A BlockingQueuedConnection can be useful to do thread communication when you want to invoke afunction in another thread and wait for the answer before it is finished. However, it must be donewith care.

The dangers of BlockingQueuedConnection

You must be careful in order to avoid deadlocks.

Obviously, if you connect two objects using BlockingQueuedConnection living on the same thread,you will deadlock immediately. You are sending an event to the sender's own thread and then are locking thethread waiting for the event to be processed. Since the thread is blocked, the event will never beprocessed and the thread will be blocked forever. Qt detects this at run time and prints a warning,but does not attempt to fix the problem for you.It has been suggested that Qt could then just do a normal DirectConnection if both objects are inthe same thread. But we choose not to because BlockingQueuedConnection is something that can only beused if you know what you are doing: You must know from which thread to what other thread theevent will be sent.

The real danger is that you must keep your design such that if in your application, you do aBlockingQueuedConnection from thread A to thread B, thread B must never wait for thread A, or you willhave a deadlock again.

When emitting the signal or calling QMetaObject::invokeMethod(), you must not have any mutex lockedthat thread B might also try locking.

A problem will typically appear when you need to terminate a thread using a BlockingQueuedConnection, for example in thispseudo code:

You cannot just call wait here because the child thread might have already emitted, or is about to emitthe signal that will wait for the parent thread, which won't go back to its event loop. All the thread cleanup information transfer must only happen withevents posted between threads, without using wait(). A better way to do it would be:

The downside is that MyOperation::cleanup() is now called asynchronously, which may complicate the design.

Conclusion

Qt Creator Signals And Slots Tutorial Key

This article should conclude the series. I hope these articles have demystified signals and slots,and that knowing a bit how this works under the hood will help you make better use of them in yourapplications.

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.

Qt Creator Signals And Slots Tutorial
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

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:

Qt Creator Signals And Slots Tutorial Download

Writing on the basis of indicators:

Qt Creator Signals And Slots Tutorial Free

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

Qt Creator Signals And Slots Tutorial For Beginners

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.

Qt Designer Signals And Slots Tutorial

Video