Qt5 信号/时隙语法,带过载信号和 lambda

Qt5 Signal/Slot syntax w/ overloaded signal & lambda

本文关键字:信号 lambda 时隙 语法 Qt5      更新时间:2023-10-16

我正在使用Signal/Slot连接的新语法。它对我来说很好,除非我试图连接过载的信号。

MyClass : public QWidget
{
    Q_OBJECT
public:
    void setup()
    {
        QComboBox* myBox = new QComboBox( this );
        // add stuff
        connect( myBox, &QComboBox::currentIndexChanged, [=]( int ix ) { emit( changedIndex( ix ) ); } ); // no dice
        connect( myBox, &QComboBox::editTextChanged, [=]( const QString& str ) { emit( textChanged( str ) ); } ); // this compiles
    }
private:
signals:
    void changedIndex( int );
    void textChanged( const QString& );
};

区别在于currentIndexChanged是重载的(int和const QString&types),而editTextChanged不是。非过载信号连接良好。过载的一个没有。我想我错过了什么?对于GCC 4.9.1,我得到的错误是

no matching function for call to ‘MyClass::connect(QComboBox*&, <unresolved overloaded function type>, MyClass::setup()::<lambda()>)’

您需要通过如下方式显式选择所需的重载:

connect(myBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [=]( int ix ) { emit( changedIndex( ix ) ); });

由于Qt 5.7,提供了方便的宏qOverload来隐藏铸造细节:

connect(myBox, qOverload<int>(&QComboBox::currentIndexChanged), [=]( int ix ) { emit( changedIndex( ix ) );