Qt5信号/槽语法:带有重载信号和lambda表达式

7

我正在使用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&类型),而editTextChanged不是。非重载的信号可以正常连接。重载的则不行。我猜我漏掉了什么?使用GCC 4.9.1,我得到的错误信息是:

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

1
可能是在Qt 5中连接超载的信号和槽的重复问题。 - cmannett85
1个回答

15

你需要通过类似这样的强制类型转换来明确选择你想要的重载:

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

谢谢...还不确定这种相当复杂的方式是否值得专业人士去尝试...但至少我知道了! - kiss-o-matic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接