[go: up one dir, main page]

Differences between String-Based and Functor-Based Connections

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.

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:

    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.

    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:

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:

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.

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

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:

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:

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

    // Connect QML signal to C++ slot
    connect(qmlObj, SIGNAL(qmlSignal(QString)),
            cppObj, SLOT(cppSlot(QString)));

    // Connect C++ signal to QML slot
    connect(cppObj, SIGNAL(cppSignal(QVariant)),
            qmlObj, SLOT(qmlSlot(QVariant)));

Note: All JavaScript functions in QML take parameters of var type, which maps to the QVariant type in C++, unless they use type annotations. See Invoking QML Methods for further details.

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:

public slots:
    void printNumber(int number = 42) {
        qDebug() << "Lucky number" << number;
    }

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:

DemoWidget::DemoWidget(QWidget *parent) : QWidget(parent) {

    // OK: printNumber() will be called with a default value of 42
    connect(qApp, SIGNAL(aboutToQuit()),
            this, SLOT(printNumber()));

    // ERROR: Compiler requires compatible arguments
    connect(qApp, &QCoreApplication::aboutToQuit,
            this, &DemoWidget::printNumber);
}

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

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

    auto slider = new QSlider(this);
    auto lcd = new QLCDNumber(this);

    // String-based syntax
    connect(slider, SIGNAL(valueChanged(int)),
            lcd, SLOT(display(int)));

    // Functor-based syntax
    connect(slider, &QSlider::valueChanged,
            lcd, qOverload<int>(&QLCDNumber::display));

See also qOverload().

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