基于字符串的连接和基于函子的连接之间的差异

从 Qt 5.0 起,Qt 提供 2 种不同方式来编写 信号槽连接 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.

基于字符串 基于函子
类型校验的完成在... 运行时 编译时
可以履行隐式类型转换 Y
可以将信号连接到 Lambda 表达式 Y
Can connect signals to slots which have more arguments than the signal (using default parameters) Y
可以将 C++ 函数连接到 QML 函数 Y
Selecting an instance of an overloaded signal or slot is... Simple Complex

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

类型校验和隐式类型转换

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 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()));
    // ...
					

使连接到 Lambda 表达式

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 () 和 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.

将 C++ 对象连接到 QML 对象

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

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

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!"' .

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

使用槽默认参数连接到具有较少参数的信号

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, 使连接到 Lambda 表达式 .

选择重载的信号和槽

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.

例如, QLCDNumber has three versions of the display() 槽:

  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, first alternative
    connect(slider, &QSlider::valueChanged,
            lcd, static_cast<void (QLCDNumber::*)(int)>(&QLCDNumber::display));
    // Functor-based syntax, second alternative
    void (QLCDNumber::*mySlot)(int) = &QLCDNumber::display;
    connect(slider, &QSlider::valueChanged,
            lcd, mySlot);
    // Functor-based syntax, third alternative
    connect(slider, &QSlider::valueChanged,
            lcd, QOverload<int>::of(&QLCDNumber::display));
    // Functor-based syntax, fourth alternative (requires C++14)
    connect(slider, &QSlider::valueChanged,
            lcd, qOverload<int>(&QLCDNumber::display));
					

另请参阅 qOverload ().