Search code examples
visual-studioc++11qt5signals-slots

How can I use Qt5 connect() on a slot with default parameters


I have some code that looks something like this:

class MyClass : public QObject
{
    Q_OBJECT

signals:
    void SetValue(float value);

public slots:
    void OnSetValue(float value, bool fromDatabase = false);
}

connect(this, SIGNAL(SetValue(float)), this, SLOT(OnSetValue(float)));

This works fine but I want to take advantage of Qt5's new signal/slot syntax (and remove the macros). If I change the connect() to this:

connect(this, &MyClass::SetValue, this, &MyClass::OnSetValue);

I get (in Visual Studio 2013):

error C2338: The slot requires more arguments than the signal provides

I could create an intermediary function that calls OnSetValue() and allows the default parameters to be set but that seems like a waste of code. What's a better way of solving this?


Solution

  • The link that sim642 provided also stated that the new connect syntax "can be used with c+11 lambda expressions". For the above example I was able to use:

    connect(this, &MyClass::SetValue, [=](float value) { OnSetValue(value); });
    

    which is slightly more complicated but is less code than adding an intermediary function and does still provide compile-time checking.

    Igor Tandetnik provided a better version above:

    connect(this, &MyClass::SetValue, [this](float value){ OnSetValue(value); });
    

    This replaces [=] (enables the lambda to capture all the automatic variables in scope by value) with [this], reducing the scope of the lambda and the possibility of error.