Unsolved Calling an intermediate function when connecting Signals and Slots
-
I am trying to connect the valueChanged() signal from QSlider to the setText() slot of a QLabel, but I want to call an intermediate function to format the string and check for some edge cases. For instance, if the QSlider is at its minimum value of 0, the text in the QLabel should be "---". not "0".
Is there a way I can call this function with the int value from QSlider::valueChanged() signal, and then pass that value to the QLabel::setText() slot?
I have tried this, but the syntax is not correct. (I get a "No such slot" error).
connect(mySld, SIGNAL(valueChanged(int)), myLbl, SLOT(setText(getLabelText(int))));
QString MyClass::getLabelText(int value){ if (value > 0) return QString::number(value); else return "---"; }
-
You can use a lambda for this:
connect(mySld, &QSlider::valueChanged, myLbl, [=](int v) { myLbl->setText(getLabelText(v)); });
-
That works great! I was trying to stick to the updated SIGNAL/SLOT syntax but this does exactly what I needed it to do. Thank you.
-
SIGNAL
/SLOT
macros are the remnant of the pre c++11 era. I would suggest to stick to the pointer based syntax - faster, more flexible and less error prone. -
@Chris-Kawa said in Calling an intermediate function when connecting Signals and Slots:
[=](int v) { myLbl->setText(getLabelText(v)); }
I set config on .pro file
CONFIG += c++11
But I still can't use SIGNAL/SLOT syntax with lambda
-
What error do you get? What Qt version do you use?
-
@Kien-Bui
SIGNAL
/SLOT
macro syntax is based on parsing strings. It doesn't work with lambdas. -
@Kien-Bui
hi
for an intro to the new syntax , please see here
https://wiki.qt.io/New_Signal_Slot_Syntax