Is it possible to use a tuple and a loop for QObject::connect?
-
I was wondering if there was a way to clean up how many lines of code I have in the constructor while dealing with a connect.
I was thinking of having a
std::vector<std::tuple<QObject*,std::function<void()>,std::function<void()>>> connections;
Where it would look like this in a private member of a class:
const std::vector<std::tuple<QObject*,std::function<void()>,std::function<void()>>> connections = { std::make_tuple(mySlider, std::bind(&QSlider::sliderReleased,mySlider), std::bind(&Foo::onSliderChanged,this)), . . . };
However, when I tried this doing:
for (const auto &e : connections) connect(std::get<0>(e),SIGNAL(std::get<1>(e)),this,SLOT(std::get<2>(e)));
None of the connections would connect, I would get an error like:
No such slot Foo::std::get<1>(e)
.I thought it was a clever attempt. And honestly I am just wondering if there is a way to make it look cleaner instead of having 20+ lines eating up my constructor. It would be nice if I could do it this way somehow.
-
Hi,
SIGNAL is a macro. I think you are looking for the new-style connect overload that uses function pointers.
-
https://doc.qt.io/qt-5/signalsandslots.html
The first example of
QObject::connect
, quite literally. -
See also https://doc.qt.io/qt-5/signalsandslots-syntaxes.html for a comparison between the old and new
connect()
syntaxes.