Qt5 Signal/Slot syntax w/ overloaded signal & lamb

2020-07-14 05:13发布

问题:

I'm using the new syntax for Signal/Slot connections. It works fine for me, except when I try to connect a signal that's overloaded.

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

The difference is currentIndexChanged is overloaded (int, and const QString& types) but editTextChanged is not. The non-overloaded signal connects fine. The overloaded one doesn't. I guess I'm missing something? With GCC 4.9.1, the error I get is

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

回答1:

You need to explicitly select the overload you want by casting like this:

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

Since Qt 5.7, the convenience macro qOverload is provided to hide the casting details:

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


标签: c++ lambda qt5