Qt Slots And Signals

Qt Slots And Signals Average ratng: 4,6/5 485 reviews

I. Principle of Signal Slot Mechanism

From the signals slots documentation: 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.). Enter any casino, and the biggest bets are always on the baccarat tables. With Signals And Slots In Qt online casinos, players can enjoy the same level of excitement on live dealer baccarat games. Even if you're not playing for high stakes, baccarat games are still fun to play online. Qt already provides signals and slots for its classes, which you can use in your application. For example, QPushButton has a signal clicked, which will be triggered when the user clicks on the button. The QApplication class has a slot quit function, which can be called when you want to terminate your application. The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments. QtScript and QML would have hardly been possible without that ability. Code for this videothis video we will learn How Qt Signals and Slots Wor.

1. Brief introduction of signal slot

The signal slot is an implementation of the observer mode, which has the following characteristics:
A. A signal is an event that can be observed, or at least a notification that an event has occurred.
B. A slot is an observer, usually a function called when the observed object changes, or when the signal is sent out.
C. The connection between signal and groove forms an observer-observer relationship.
D. When an event or state changes, the signal will be sent; at the same time, the sender is obliged to call all registered functions (slots) interested in the event (signal).
Signals and slots are many-to-many relationships. A signal can connect multiple slots, and a slot can monitor multiple signals.
Signal slot has nothing to do with language. There are many ways to realize signal slot. Different implementation mechanisms will lead to different signal slots. The term signal slot originally came from Trolltech's Qt library. Because of its advanced design concept, it immediately attracted the attention of the computer science community and proposed a variety of different implementations. At present, signal slot is still one of the core of Qt library. Many other libraries provide similar implementations, and even some tool libraries specially providing this mechanism have emerged.
Signal slot is an efficient communication interface between Qt objects and their derivatives. It is the core feature of Qt and an important difference between Qt and other toolkits. Signal slot is completely independent of the standard C/C++ language, so in order to properly handle the signal and slot, we must rely on a Qt tool that becomes MOC (Meta Object Compiler). MOC tool is a C++ preprocessor, which can automatically generate additional code for high-level event processing.

2. Implementation of Different Platforms

The message mechanism in MFC does not use the virtual function mechanism in C++, because there are too many messages and the virtual function is too expensive. In Qt, the virtual function mechanism in C++ is not used, but the signal slot mechanism is adopted for the same reason. More deeply, there are only two underlying implementation mechanisms for polymorphism, one is to look up tables by name, the other is to look up tables by location. Both methods have their advantages and disadvantages, and the virtual function mechanism of C++ unconditionally adopts the latter. The problem is that when subclasses are seldom overloaded and base classes are implemented, the overhead is too large. In addition, there are many neutron classes in interface programming. Basically, the virtual function mechanism of C++ is too inefficient, so the compilers of libraries have to make a living by themselves. Road, of course, is actually the flaw of C++ language itself.

2. Case Analysis of Qt Signal Slot

1. Examples of Signal Slot Use

Using a simple example:

Main function:

2. SIGNAL and SLOT macros

SIGNAL and SLOT macros are defined in the file / src/corelib/kernel/Qobjectdefs.h.

SIGNAL and SLOT macros use a precompiler to convert some parameters into strings, and add encoding before.
In debugging mode, if signal's connection fails, the corresponding file location will be indicated when warning message is prompted. qFlagLocation is used to locate the corresponding line information of the code, registering the address information of the corresponding code into a table with two entries.
The code for SIGNAL and SLOT macros in the Object.h file is as follows:

Object.i file is obtained by pre-compiling the Object.h file.
Pre-compiled with G++:
g++ -E Object.h -o Object.i -I/usr/local/Trolltech/Qt-4.8.6/include/QtCore -I/usr/local/Trolltech/Qt-4.8.6/include -I.
The results in the Object.i file are as follows:

3. Meta-objects of classes

When the program is compiled, make calls MOC to parse the project source code and generates the moc_xx.cpp file of the corresponding class.

The static member staticMetaObject is populated with the following values:
const QMetaObject superdata; //metadata represents the metadata of the base class of the class, which is populated with the metadata pointer of the base class & QWidget:: StaticMetaObject
const char stringdata; //meta data signature tag, filled with qt_meta_stringdata_Widget.data
Constuint*data; //metadata index array pointer, filled with qt_meta_data_Widget
const QMetaObject **extradata; // Extended metadata table pointer, internal filled as function pointer qt_static_metacall.
staticMetaObjectExtraData is initialized as follows:

The internal member static_metacall of the QMetaObjectExtraData type is a function pointer to Object::qt_static_metacall.
Object's memory layout is as follows:
Object memory layout already contains static members staticMetaObject and
staticMetaObjectExtraData member.

QObject:: d_ptr - > metaObject is only used by dynamic metaobjects (QML objects), so in general, the virtual function metaObject() returns only staticMetaObject of the class.

4. Metadata table

When Qt program compiles, make calls MOC tool to analyze the source file. If a class contains Q_OBJECT macro, MOC generates the corresponding moc_xx.cpp file.
In the content of moc_Object.cpp file:
Object's metadata is as follows:

The introspection table is an uint array, divided into five parts: the first part, content, is divided into nine lines. The first line of revision refers to the version number of the code generated by MOC (Qt4 is 6, Qt5 is 7). The second class name, the class name, is an index that points to a location in the string table (in this case, bit 0).

5. Realization of Signal

MOC implements the signal in the generated moc_xxx.cpp file, creates an array of pointers to parameters, and passes the array of pointers to the QMetaObject::activate function. The first element of the array is the return value. The median value in this case is 0, because the return value is void. The third parameter passed to the activate function is the index of the signal (0 in this case).

6. Call of slot function

The slot function is invoked by using the index position of the qt_static_metacall function:

7. Index in meta-objects

In each QMetaObject object, slots, signals, and other object callable functions are assigned an index starting at 0. The index is ordered, the signal is in the first place, the slot is in the second place, and the other functions are in the last place. This index is internally referred to as a relative index and does not contain the index bits of the parent object.
In order to realize the index of other functions contained in the inheritance chain, an offset is added to the relative index to obtain the absolute index. Absolute index is an index used in the public API, returned by a function similar to QMetaObject::indexOf(Signal, Slot, Method).
The connection mechanism uses vectors indexed by signals. But in the vector, all slots also occupy a certain space, usually in an object, the number of slots is more than the signal. So starting with Qt 4.6, we use a new internal implementation that contains only the signal index.

8. Connection of signal and slot

When starting the connection, the first thing Qt needs to do is to find the index of the desired signal and slot. Qt will look up the string table of the meta-object to find the corresponding index.
Then, create a QObjectPrivate::Connection object and add it to the internal list.
Since multiple slots are allowed to connect to the same signal, it is necessary to add a list of connected slots for each signal. Each connection must contain an index of the receiving object and slot. When the receiving object is destroyed, the corresponding connection can also be destroyed automatically. So each receiving object needs to know who is connected to it so that it can clean up the connection.
The private data QObjectPrivate of the QObject object is as follows:

Each QObject object has a linked list container QObjectConnectionListVector *connectionLists: associates each signal with a linked list of QObjectPrivate::Connection.
The implementation of QObject::connect function is as follows:

The main function of QObject::connect function is to find the relative index of slot function in the meta-object of the recipient object, the relative index of slot function in the meta-object of the recipient object, and finally call QMetaObjectPrivate::connect to connect the signal with the slot. The meta-object of QObject and its derivative class object has a QObjectConnectionListVector connection list container when it is created. The function of QObject:: connection is to add new connections to the connection list of corresponding signals of the connection list container of meta-object attached to the sender (a signal may connect multiple slot functions). .

Each QObject and its derived class object has a QObjectConnectionListVector *connectionLists connection list container, which takes the index of the signal as the index of the container and associates each signal with a QObjectPrivate::ConnectionList linked list. At the same time, a slot function connected in the QObjectPrivate::ConnectionList list may be one of the slot function lists of the recipient object. The list of each recipient object is as follows:
The prev pointer of senderList is a pointer. This is because it does not really point to the previous node, but to the next pointer in the previous node. This pointer is only used when the connection is destroyed and cannot be traversed backwards. It allows no special processing to be added to the first element.
The ConnectionList stored in the container is as follows:

Each ConnectionList type element is a two-way linked list that stores all connections to the signal. The connection type Connection structure is as follows:

QMetaObjectPrivate::connect function source code is as follows:
// A new connection is added to the connection list of the corresponding signal in the connection list container of the signal sender, where the index of the connection list joined by the connection is the index of the signal.

9. Signal Emission

When emit transmits signals, the signal function implemented by MOC is actually called, and the QMetaObject::activate() function is called inside the signal function.

The qt_static_metacall function is called inside the qt_metacall function.

10. Call of slot function

The slot function finally calls the corresponding slot function according to the parameters through the qt_static_metacall function.

11. Function Call Process Analysis

Debugging breakpoints inside onAgeChanged(int age) slot functions.
The resulting function call stack is as follows:
Function call stack analysis:
Object::qt_metacall function calls Object::setAge function, setAge calls Object::ageChanged signal function, ageChanged signal function calls QMetaObject::activate function, activate function calls Object::qt_static_metacall function, and finally qt_static_metacall function calls slot function onA inside. GeChanged.
So in this case, when ob.setProperty('age', QVariant(30)) is invoked, the call of QMetaProperty::Write function is triggered, and then Object::qt_metacall in moc_Object.cpp file implemented by MOC is invoked, setAge function is invoked internally, and the signal change inside Age function is transmitted, that is, Object is called. The QMetaObject::activate function of the meta-object of the Object object is called inside the ageChanged signal function, Object::ageChanged function, and the Object::qt_static_metacall function is called inside the activate function. Finally, the onAgeChanged slot function is called inside the qt_static_metacall.
In this case, the signal and slot are in the same thread, the connection type is direct connection, so it belongs to synchronous invocation and is the simplest type of invocation. QMetaObject:: Actate function actually finds the corresponding signal according to the signal link list container in the meta-object of Object object: qt_static_metacall callback function, and then callback.

3. Standard C++ Implementation of Signal Slot

1. Implementation of Qt meta-object simulation

Object class implementation:

moc_Object.cpp implementation:

2. Simulated use of signal slot

Main.cpp file:

4. Open Source Realization of Signal Slot

1,sigslot

Sigslot is a very refined C++ implementation of signal slot. The author is Sarah Thompson. The sigslot implementation has only one header file sigslot.h, which is cross-platform and thread-safe. In WebRTC, sigslot.h is the basic event processing framework, which is used in message notification and response processing of multiple modules.
sigslot repository website:
http://sigslot.sourceforge.net/

An example of Sigslot's use is as follows:

Qt connect signal slot

If sigslot.h is used in Qt project, the emit function name in sigslot.h conflicts with the emit macro in Qt, there are two ways to modify it. One is to change the emit of sigslot.h to another name, the other is to add DEFINES+=QT_NO_EMIT to the. pro file and disable the emit macro of Qt.

2,Boost.Signals

Boost.Signals implements signals/slots mode, signals are transmitted, and slots receive the signals.

Qt Private Slots

The execution order of slot function is random, and the call order can be controlled by grouping parameters.
sig.connect(1,&firstSlot);
sig.connect(2,secondSlot());

3. The difference between the realization of Qt signal slot and that of Boost signal slot

Qt Connect Slot

Boost.SignalsQt Signals and Slots
A signal is an object.Signals can only be member functions
Signaling is similar to function callsSending a signal is similar to a function call, and Qt provides an emit keyword to do this.
Signals can be global, local, or member objectsSignals can only be member functions
Any code that can access the signal object can send a signal.Only the owner of the signal can send out the signal.
A slot is any callable function or function object.Slot is a specially designed member function
You can have a return value, which can be used in multiple slotsno return value
SynchronousSynchronized or queued
Non-thread securityThread-safe, can be used across threads
When and only if the slot is traceable, the connection automatically disconnects when the slot is destroyed.When the groove is destroyed, the connection will automatically disconnect (because all grooves are traceable).
Type Safety (Compiler Check)Type Safety (Operational Period Check)
The list of parameters must be exactly the sameThe slot can ignore the redundant parameters in the signal
Signals and slots can be templatesSignals and slots cannot be templates
C++ Direct ImplementationThrough meta-object realization generated by moc (both moc and meta-object system are directly implemented by C++)
No introspective mechanismThrough introspection, it can be found that connections can be automatically inferred from resource files through meta-object calls.

Qt Slots And Signals Reviews

Posted on Wed, 11 Sep 2019 07:03:16 -0400 by alimadzi