Felix Diel
Felix Diel

Reputation: 23

Connecting Signals to c++11 lambdas in QT5

I tried to connect a QDoubleSpinBox Signal to a c++11 lamda:

QObject::connect(sbox_roughness, &QDoubleSpinBox::valueChanged,
               [=]() { std::cout << "value changed" << std::endl; });

This is giving me:

error: no matching function for call to ‘Game::connect(QDoubleSpinBox*&, <unresolved overloaded function type>, Game::initGui()::<lambda()>)’
                [=]() { std::cout << "value changed" << std::endl; });
note:   no known conversion for argument 2 from ‘<unresolved overloaded function type>’ to ‘const char*’

I've tried this:

QObject::connect(sbox_roughness, static_cast<void (QDoubleSpinBox::*)(int)>(
                                   &QDoubleSpinBox::valueChanged),
               [=]() { std::cout << "value changed" << std::endl; }); 

giving me:

error: no matches converting function ‘valueChanged’ to type ‘void (class QDoubleSpinBox::*)(int)’
                                    &QDoubleSpinBox::valueChanged),

What am I missing here?

Upvotes: 2

Views: 1071

Answers (2)

QDoubleSpinBox spinbox;

QObject::connect(&spinbox, &QDoubleSpinBox::valueChanged,
                 []() { qDebug() << "value changed"; });

This fails because QDoubleSpinBox has two valueChanged signals, and it's impossible to decide which one you wanted to connect to here.

QObject::connect(&spinbox, static_cast<void (QDoubleSpinBox::*)(int)>(
                                  &QDoubleSpinBox::valueChanged),
                []() {  qDebug() << "value changed"; });

This fails because QDoubleSpinBox does not have a valueChanged(int) signal.

This will work:

QObject::connect(&spinbox, static_cast<void (QDoubleSpinBox::*)(double)>(
                                  &QDoubleSpinBox::valueChanged),
                []() {  qDebug() << "value changed"; });

QObject::connect(&spinbox, static_cast<void (QDoubleSpinBox::*)(const QString &)>(
                                  &QDoubleSpinBox::valueChanged),
                []() {  qDebug() << "value changed"; });

Upvotes: 3

Evgeny
Evgeny

Reputation: 4010

You faced arguments missmatch. Should be like this:

QObject::connect(sbox_roughness, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
           [=](double val) { std::cout << "value changed" << std::endl; });

Upvotes: 1

Related Questions