[Qt-interest] Idea: QSignalMapper with std::function (esp. for C++0x lambdas)
Ville M. Vainio
vivainio at gmail.com
Fri Feb 19 08:59:57 CET 2010
Anyone done a version of QSignalMapper that supports std::function
mapping, instead of the more pedestrian int, string, QWidget mapping?
This would provide a convenient way to specify triggered behavior
inline, instead of either making a new slot, or relying on the
already-existing slots.
It would work something like (with C++0x lambda syntax):
QString text = texts[i];
int random_number = rand()
QPushButton *button = new QPushButton(text);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
// (note that we have a new version of setMapping that takes std::function)
signalMapper->setMapping(button, [=]()
{ qDebug() << "Pressed: " << text << " random number was " <<
random_number; }
);
( I have never actually used c++0x lamda, so this may be horribly wrong )
Note how I'm using both text and random_number in the "slot". If I was
to do this with the existing slot mechanism, I'd have to store
random_number in an attribute (which can be incredibly tedious for
quick one-off operations - more so if you are doing this in a loop and
have to store a collection of random_number).
While waiting for C++0x to set things right, you can use boost::lambda.
Not having closures is one of the things still bothering me greatly
about C++, since this problem is gradually disappearing Qt stands to
benefit from it. Obviously, in the meantime people who have the luxury
to use modern C++ compilers can copy the QSignalMapper implementation
and create a new class with this feature, unless there is a logical
flaw I'm not seeing...
--
Ville M. Vainio
http://tinyurl.com/vainio
More information about the Qt-interest-old
mailing list