Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt5 Signal/Slot syntax w/ overloaded signal & lambda

Tags:

c++

lambda

qt5

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()>)’
like image 537
kiss-o-matic Avatar asked Jul 01 '15 14:07

kiss-o-matic


People also ask

Can we connect one signal with multiple slots?

You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)

How many signals can be connected to a slot in Qt?

You can have as many signals you want connected to one slot and vice versa. If several slots are connected to one signal, the slots will be executed one after the other, in the order they have been connected, when the signal is emitted.

How do you create a signal and slot in Qt?

There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed); There are several advantages to using QObject::connect() with function pointers.

How signal and slot works in Qt?

The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments.


1 Answers

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 ) );
like image 173
Robert Avatar answered Oct 03 '22 01:10

Robert