Domanda

Let'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));

output: just says that slot f doesn't exist.

or

QString f="SLOT(function())";
//conversion to const char*
connect (randomobject, SIGNAL(randomsignal()), this, f);
output: Use the SLOT or SIGNAL macro to connect 

work.

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

È stato utile?

Soluzione

You can check out definition of SLOT in qobjectdefs.h:

#ifndef QT_NO_DEBUG
# define SLOT(a)     qFlagLocation("1"#a QLOCATION)
# define SIGNAL(a)   qFlagLocation("2"#a QLOCATION)
#else
# define SLOT(a)     "1"#a
# define SIGNAL(a)   "2"#a
#endif

Which means SLOT("func()") simply converts to "1func()" after preprocessing. So you can write:

Test *t = new Test; // 'Test' class has slot void func()
QString str = "func()";

QPushButton *b = new QPushButton("pressme");
QObject::connect(b, SIGNAL(clicked()), t, QString("1" + str).toLatin1()); // toLatin1 converts QString to QByteArray

When you'll show button and press it, slot func() from Test will be invoked.

Note that 'connect' takes 'const char *' as second and fourth parameters type, so you have to convert QString to 'const char *' or 'QByteArray' (which will be casted to char pointer).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top