PDA

View Full Version : Qt connect without SLOT macro



webstar
18th April 2014, 20:29
et's say I have a string containing "function()", where function() is a slot in a class, and I would like to connect that slot with any signal, but using that string. Neither


QString f="function()";
connect (randomobject, SIGNAL(randomsignal()), this, SLOT(f));

or


QString f="SLOT(function())";
//conversion to const char*
connect (randomobject, SIGNAL(randomsignal()), this, f);

work.

Is there a way to do something similar? It's important that it's a string and not a function pointer.

stampede
18th April 2014, 23:33
I don't think you can use this string in "connect" statement directly, but you can connect the signal to a regular slot, in which you call QMetaObject::invokeMethod (http://qt-project.org/doc/qt-4.8/qmetaobject.html#invokeMethod)


#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[]) {
QApplication a(argc, argv);
const QString slotName = "show"; // no parentheses
const QByteArray ba = slotName.toLocal8Bit();
const char * c_str = ba.constData();
QWidget w;
QMetaObject::invokeMethod(&w, c_str);
return a.exec();
}

anda_skoa
20th April 2014, 15:07
QString f="SLOT(function())";
//conversion to const char*
connect (randomobject, SIGNAL(randomsignal()), this, f);


That is almost there, you just need to get a slightly different string


QString f=SLOT(function());
connect (randomobject, SIGNAL(randomsignal()), this, f.toAscii().constData());


I.e. the SLOT() macro creates a string, with the function name, any argument types and some slot specific prefix.

Cheers,
_