Qt Slots Keyword
EnArBgDeElEsFaFiFrHiHuItJaKnKoMsNlPlPtRuSqThTrUkZh
This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt 5.
- Qtcreator treats 'signals' as being a keyword. This does make sense for qt-based code, but some of my non-qt-based code makes heavy use of 'slots' as name for a member variable. In these cases the code model is completely broken. It may be a good idea to make this configurable.
- Traditional syntax: SIGNAL and SLOT QtCore.SIGNAL and QtCore.SLOT macros allow Python to interface with Qt signal and slot delivery mechanisms. This is the old way of using signals and slots. The example below uses the well known clicked signal from a QPushButton. The connect method has a non python-friendly syntax.
- Differences between String-Based and Functor-Based Connections (Official documentation)
- Introduction (Woboq blog)
- Implementation Details (Woboq blog)
Note: This is in addition to the old string-based syntax which remains valid.
As the signal is emitted in the same thread as the recieving object, Qt::AutoConnection will assign Qt::DirectConnection. In simple words, I would like to know if the code after the 'emit' keyword will be executed (always) after every slot associated with the signal is called and finished. One of the key features of Qt is its use of signals and slots to communicate between objects. Their use encourages the development of reusable components. A signal is emitted when something of potential interest happens. A slot is a Python callable.
- 1Connecting in Qt 5
- 2Disconnecting in Qt 5
- 4Error reporting
- 5Open questions
Connecting in Qt 5
There are several ways to connect a signal in Qt 5.
Old syntax
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)
New: connecting to QObject member
Here's Qt 5's new way to connect two QObjects and pass non-string objects:
Pros
- Compile time check of the existence of the signals and slot, of the types, or if the Q_OBJECT is missing.
- Argument can be by typedefs or with different namespace specifier, and it works.
- Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
- It is possible to connect to any member function of QObject, not only slots.
Cons
- More complicated syntax? (you need to specify the type of your object)
- Very complicated syntax in cases of overloads? (see below)
- Default arguments in slot is not supported anymore.
New: connecting to simple function
The new syntax can even connect to functions, not just QObjects:
Pros
- Can be used with std::bind:
- Can be used with C++11 lambda expressions:
Cons
- There is no automatic disconnection when the 'receiver' is destroyed because it's a functor with no QObject. However, since 5.2 there is an overload which adds a 'context object'. When that object is destroyed, the connection is broken (the context is also used for the thread affinity: the lambda will be called in the thread of the event loop of the object used as context).
Disconnecting in Qt 5
As you might expect, there are some changes in how connections can be terminated in Qt 5, too.
Old way
You can disconnect in the old way (using SIGNAL, SLOT) but only if
- You connected using the old way, or
- If you want to disconnect all the slots from a given signal using wild card character
Symetric to the function pointer one
Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card)In particular, does not work with static function, functors or lambda functions.
New way using QMetaObject::Connection
Works in all cases, including lambda functions or functors.
Asynchronous made easier
With C++11 it is possible to keep the code inline
Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:
Another example using QHttpServer : http://pastebin.com/pfbTMqUm
Error reporting
Tested with GCC.
Fortunately, IDEs like Qt Creator simplifies the function naming
Missing Q_OBJECT in class definition
Qt Slots Keywords
Type mismatch
Open questions
Default arguments in slot
Qt Slots Keyword
If you have code like this:
The old method allows you to connect that slot to a signal that does not have arguments.But I cannot know with template code if a function has default arguments or not.So this feature is disabled.
There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal.This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.
Overload
As you might see in the example above, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting, e.g. a connection that previously was made as follows:
connect(mySpinBox, SIGNAL(valueChanged(int)), mySlider, SLOT(setValue(int));
cannot be simply converted to:
...because QSpinBox has two signals named valueChanged() with different arguments. Instead, the new code needs to be:
Unfortunately, using an explicit cast here allows several types of errors to slip past the compiler. Adding a temporary variable assignment preserves these compile-time checks:
Some macro could help (with C++11 or typeof extensions). A template based solution was introduced in Qt 5.7: qOverload
The best thing is probably to recommend not to overload signals or slots …
… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.
Disconnect
Should QMetaObject::Connection have a disconnect() function?
The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that takes a closure.One could add a list of objects in the disconnection, or a new function like QMetaObject::Connection::require
Callbacks
Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot.This does not work for the new method.If one wants to do callback C++ way, one should use std::functionBut we cannot use STL types in our ABI, so a QFunction should be done to copy std::function.In any case, this is irrelevant for QObject connections.
Slots in D-Bus adaptors are declared just like normal, public slots, but their parameters must follow certain rules (see The Qt D-Bus Type System for more information). Slots whose parameters do not follow those rules or that are not public will not be accessible via D-Bus.
Slots can have one parameter of type const QDBusMessage &
, which must appear at the end of the input parameter list, before any output parameters. This parameter, if present, will be initialized with a copy of the current message being processed, which allows the callee to obtain information about the caller, such as its connection name.
Slots can be of three kinds:
- Asynchronous
- Input-only
- Input-and-output
Asynchronous Slots
Asynchronous slots are those that do not normally return any reply to the caller. For that reason, they cannot take any output parameters. In most cases, by the time the first line of the slot is run, the caller function has already resumed working.
However, slots must not rely on that behavior. Scheduling and message-dispatching issues could change the order in which the slot is run. Code intending to synchronize with the caller should provide its own method of synchronization.
Asynchronous slots are marked by the keyword Q_NOREPLY in the method signature, before the void
return type and the slot name. The quit()
slot in the D-Bus Complex Ping Pong Example is an example of this.
Input-Only Slots
Input-only slots are normal slots that take parameters passed by value or by constant reference. However, unlike asynchronous slots, the caller is usually waiting for completion of the callee before resuming operation. Therefore, non-asynchronous slots should not block or should state it its documentation that they may do so.
Input-only slots have no special marking in their signature, except that they take only parameters passed by value or by constant reference. Optionally, slots can take a QDBusMessage parameter as a last parameter, which can be used to perform additional analysis of the method call message.
Input and Output Slots
Like input-only slots, input-and-output slots are those that the caller is waiting for a reply. Unlike input-only ones, though, this reply will contain data. Slots that output data may contain non-constant references and may return a value as well. However, the output parameters must all appear at the end of the argument list and may not have input arguments interleaved. Optionally, a QDBusMessage argument may appear between the input and the output arguments.
Automatic Replies
Method replies are generated automatically with the contents of the output parameters (if there were any) by the Qt D-Bus implementation. Slots need not worry about constructing proper QDBusMessage objects and sending them over the connection.
However, the possibility of doing so remains there. Should the slot find out it needs to send a special reply or even an error, it can do so by using QDBusMessage::createReply() or QDBusMessage::createErrorReply() on the QDBusMessage parameter and send it with QDBusConnection::send(). The Qt D-Bus implementation will not generate any reply if the slot did so.
Warning: When a caller places a method call and waits for a reply, it will only wait for a limited amount of time. Slots intending to take a long time to complete should make that fact clear in documentation so that callers properly set higher timeouts.
Delayed Replies
In some circumstances, the called slot may not be able to process the request immediately. This is frequently the case when the request involves an I/O or networking operation which may block.
If this is the case, the slot should return control to the application's main loop to avoid freezing the user interface, and resume the process later. To accomplish this, it should make use of the extra QDBusMessage
parameter at the end of the input parameter list and request a delayed reply.
We do this by writing a slot that stores the request data in a persistent structure, indicating to the caller using QDBusMessage::setDelayedReply(true) that the response will be sent later.
The use of QDBusConnection::sessionBus().send(data->reply) is needed to explicitly inform the caller that the response will be delayed. In this case, the return value is unimportant; we return an arbitrary value to satisfy the compiler.
When the request is processed and a reply is available, it should be sent using the QDBusMessage
object that was obtained. In our example, the reply code could be something as follows:
As can be seen in the example, when a delayed reply is in place, the return value(s) from the slot will be ignored by Qt D-Bus. They are used only to determine the slot's signature when communicating the adaptor's description to remote applications, or in case the code in the slot decides not to use a delayed reply.
The delayed reply itself is requested from Qt D-Bus by calling QDBusMessage::reply() on the original message. It then becomes the resposibility of the called code to eventually send a reply to the caller.
Warning: When a caller places a method call and waits for a reply, it will only wait for a limited amount of time. Slots intending to take a long time to complete should make that fact clear in documentation so that callers properly set higher timeouts.
See also Using Qt D-Bus Adaptors, Declaring Signals in D-Bus Adaptors, The Qt D-Bus Type System, QDBusConnection, and QDBusMessage.
© 2021 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.