Qt Signal And Slot Arguments Are Not Compatible

Posted on  by 



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. It is necessary to inform the object, its signal (via macro.

It would be possible to have the slots to which the resized and moved signals are connected check the new position or size of the circle and respond accordingly, but it's more convenient and requires less knowledge of circles by the slot functions if the signal that is sent can include that information. You can't use slots as target for callbacks or invoke a slot by name. This was certainly not a design goal of Qt signal/slots, but it makes the mechanism less powerful than C#'s delegates and creates the need for a second mechanism The connect syntax is unnecessary complicated because of the SIGNAL/SLOT macros.

EnArBgDeElEsFaFiFrHiHuItJaKnKoMsNlPlPtRuSqThTrUkZh

This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt 5.

  • 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.

  • 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

Compatible

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

Signal

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:

Qt Signal And Slot Arguments Are Not Compatible

Another example using QHttpServer : http://pastebin.com/pfbTMqUm

Error reporting

Qt Signal And Slot Arguments Are Not Compatible

Tested with GCC.

Fortunately, IDEs like Qt Creator simplifies the function naming

Missing Q_OBJECT in class definition

Type mismatch

Open questions

Default arguments in slot

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 …

Qt Signal And Slot Arguments Are Not Compatible To Be

… 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.

Retrieved from 'https://wiki.qt.io/index.php?title=New_Signal_Slot_Syntax&oldid=34943'

From Qt 5.0 onwards, Qt offers two different ways to write signal-slot connections in C++: The string-based connection syntax and the functor-based connection syntax. There are pros and cons to both syntaxes. The table below summarizes their differences.

String-basedFunctor-based
Type checking is done at...Run-timeCompile-time
Can perform implicit type conversionsY
Can connect signals to lambda expressionsY
Can connect signals to slots which have more arguments than the signal (using default parameters)Y
Can connect C++ functions to QML functionsY

The following sections explain these differences in detail and demonstrate how to use the features unique to each connection syntax.

Type Checking and Implicit Type Conversions

String-based connections type-check by comparing strings at run-time. There are three limitations with this approach:

  1. Connection errors can only be detected after the program has started running.
  2. Implicit conversions cannot be done between signals and slots.
  3. Typedefs and namespaces cannot be resolved.

Limitations 2 and 3 exist because the string comparator does not have access to C++ type information, so it relies on exact string matching.

In contrast, functor-based connections are checked by the compiler. The compiler catches errors at compile-time, enables implicit conversions between compatible types, and recognizes different names of the same type.

Qt Signal And Slot Arguments Are Not Compatible Modems

For example, only the functor-based syntax can be used to connect a signal that carries an int to a slot that accepts a double. A QSlider holds an int value while a QDoubleSpinBox holds a double value. The following snippet shows how to keep them in sync:

The following example illustrates the lack of name resolution. QAudioInput::stateChanged() is declared with an argument of type 'QAudio::State'. Thus, string-based connections must also specify 'QAudio::State', even if 'State' is already visible. This issue does not apply to functor-based connections because argument types are not part of the connection.

Making Connections to Lambda Expressions

The functor-based connection syntax can connect signals to C++11 lambda expressions, which are effectively inline slots. This feature is not available with the string-based syntax.

In the following example, the TextSender class emits a textCompleted() signal which carries a QString parameter. Here is the class declaration:

Here is the connection which emits TextSender::textCompleted() when the user clicks the button:

In this example, the lambda function made the connection simple even though QPushButton::clicked() and TextSender::textCompleted() have incompatible parameters. In contrast, a string-based implementation would require extra boilerplate code.

Note: The functor-based connection syntax accepts pointers to all functions, including standalone functions and regular member functions. However, for the sake of readability, signals should only be connected to slots, lambda expressions, and other signals.

Connecting C++ Objects to QML Objects

The string-based syntax can connect C++ objects to QML objects, but the functor-based syntax cannot. This is because QML types are resolved at run-time, so they are not available to the C++ compiler.

In the following example, clicking on the QML object makes the C++ object print a message, and vice-versa. Here is the QML type (in QmlGui.qml):

Here is the C++ class:

Here is the code that makes the signal-slot connections:

Note: All JavaScript functions in QML take parameters of var type, which maps to the QVariant type in C++.

When the QPushButton is clicked, the console prints, 'QML received: 'Hello from C++!'. Likewise, when the Rectangle is clicked, the console prints, 'C++ received: 'Hello from QML!'.

See Interacting with QML Objects from C++ for other ways to let C++ objects interact with QML objects.

Using Default Parameters in Slots to Connect to Signals with Fewer Parameters

Usually, a connection can only be made if the slot has the same number of arguments as the signal (or less), and if all the argument types are compatible.

The string-based connection syntax provides a workaround for this rule: If the slot has default parameters, those parameters can be omitted from the signal. When the signal is emitted with fewer arguments than the slot, Qt runs the slot using default parameter values.

Functor-based connections do not support this feature.

Suppose there is a class called DemoWidget with a slot printNumber() that has a default argument:

Qt Signal And Slot Arguments Are Not Compatible Phones

Using a string-based connection, DemoWidget::printNumber() can be connected to QApplication::aboutToQuit(), even though the latter has no arguments. The functor-based connection will produce a compile-time error:

To work around this limitation with the functor-based syntax, connect the signal to a lambda function that calls the slot. See the section above, Making Connections to Lambda Expressions.

Selecting Overloaded Signals and Slots

Qt Signal And Slot Arguments Are Not Compatible Devices

With the string-based syntax, parameter types are explicitly specified. As a result, the desired instance of an overloaded signal or slot is unambiguous.

In contrast, with the functor-based syntax, an overloaded signal or slot must be casted to tell the compiler which instance to use.

For example, QLCDNumber has three versions of the display() slot:

  1. QLCDNumber::display(int)
  2. QLCDNumber::display(double)
  3. QLCDNumber::display(QString)

To connect the int version to QSlider::valueChanged(), the two syntaxes are:

See also qOverload().

© 2020 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.





Coments are closed