Differences between String-Based and Functor-Based Connections

From Qt 5.0 onward, 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-based

Functor-based

Type checking is done at...

Run-time

Compile-time

Can perform implicit type conversions

 

Y

Can connect signals to lambda expressions

 

Y

Can connect signals to slots which have more arguments than the signal (using default parameters)

Y

 

Can connect C++ functions to QML functions

Y

 

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.

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:

 
Sélectionnez
    auto slider = new QSlider(this);
    auto doubleSpinBox = new QDoubleSpinBox(this);

    // OK: The compiler can convert an int into a double
    connect(slider, &QSlider::valueChanged,
            doubleSpinBox, &QDoubleSpinBox::setValue);

    // ERROR: The string table doesn't contain conversion information
    connect(slider, SIGNAL(valueChanged(int)),
            doubleSpinBox, SLOT(setValue(double)));

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.

 
Sélectionnez
    auto audioInput = new QAudioInput(QAudioFormat(), this);
    auto widget = new QWidget(this);

    // OK
    connect(audioInput, SIGNAL(stateChanged(QAudio::State)),
            widget, SLOT(show()));

    // ERROR: The strings "State" and "QAudio::State" don't match
    using namespace QAudio;
    connect(audioInput, SIGNAL(stateChanged(State)),
            widget, SLOT(show()));

    // ...

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:

 
Sélectionnez
class TextSender : public QWidget {
    Q_OBJECT

    QLineEdit *lineEdit;
    QPushButton *button;

signals:
    void textCompleted(const QString& text) const;

public:
    TextSender(QWidget *parent = nullptr);
};

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

 
Sélectionnez
TextSender::TextSender(QWidget *parent) : QWidget(parent) {
    lineEdit = new QLineEdit(this);
    button = new QPushButton("Send", this);

    connect(button, &QPushButton::clicked, [=] {
        emit textCompleted(lineEdit->text());
    });

    // ...
}

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.

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):

 
Sélectionnez
Rectangle {
    width: 100; height: 100

    signal qmlSignal(string sentMsg)
    function qmlSlot(receivedMsg) {
        console.log("QML received: " + receivedMsg)
    }

    MouseArea {
        anchors.fill: parent
        onClicked: qmlSignal("Hello from QML!")
    }
}

Here is the C++ class:

 
Sélectionnez
class CppGui : public QWidget {
    Q_OBJECT

    QPushButton *button;

signals:
    void cppSignal(const QVariant& sentMsg) const;

public slots:
    void cppSlot(const QString& receivedMsg) const {
        qDebug() << "C++ received:" << receivedMsg;
    }

public:
    CppGui(QWidget *parent = nullptr) : QWidget(parent) {
        button = new QPushButton("Click Me!", this);
        connect(button, &QPushButton::clicked, [=] {
            emit cppSignal("Hello from C++!");
        });
    }
};

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

 
Sélectionnez
    auto cppObj = new CppGui(this);
    auto quickWidget = new QQuickWidget(QUrl("QmlGui.qml"), this);
    auto qmlObj = quickWidget->rootObject();