can't connect overloaded method to a lambda function



  • I can't compile the following code

    class Foo : public QWidget
    {
        Q_OBJECT
    public:
        Foo()
        {
            QSpinBox *spinBox = new QSpinBox(this);
            connect(spinBox, &QSpinBox::valueChanged, [this](int val){/*do smth*/});
        }
    };
    

    The error is

    error: no matching function for call to 'Foo::connect(QSpinBox*&, <unresolved overloaded function type>, Foo::Foo()::<lambda(int)>)'
             connect(spinBox, &QSpinBox::valueChanged, [this](int val){/*do smth*/});
                                                                                  ^
    

    I guess the problem is "unresolved overloaded function type", because actually we have two overloaded methods in class QSpinBox:

        void valueChanged(int);
        void valueChanged(const QString &);
    

    Any ideas how to help compiler to resolve the right method?

    My specs:
    GCC 4.9.2
    Qt 5.5.1


  • Qt Champions 2017

    hi
    Try

     connect(spinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [this]( int val){/*do smth*/});
    

    https://wiki.qt.io/New_Signal_Slot_Syntax

    ...because QSpinBox has two signals named valueChanged() with different arguments. Instead, the new code needs to be:
    connect(mySpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), mySlider, &QSlider::setValue);

    As you seem to think also.



  • Thanks, that works. Though, it doesn't look elegant...

    P.S. Such a syntax also works

    connect(spinBox, (void(QSpinBox::*)(int))&QSpinBox::valueChanged, this, [this]( int val){/*do smth*/});
    

  • Qt Champions 2017

    @duburlan
    I agree.
    Its not pretty.


  • Moderators

    If you don't mind writing more lines, you can make each line shorter:

    void (QSpinBox::*mySignal)(int) = &QSpinBox::valueChanged;
    
    connect(spinBox, mySignal, this, [this](int val) {
        /*do smth*/
    });
    

    See http://doc.qt.io/qt-5/signalsandslots-syntaxes.html


  • Qt Champions 2017

    far more readable :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.