3

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.

rndm
  • 137
  • 1
  • 9
  • 1
    Did you check the implementation of the SLOT macro? – D Drmmr Apr 18 '14 at 18:29
  • What is the error that you are getting? – Samer Apr 18 '14 at 18:33
  • Yes I did, and I know that SLOT basically converts what's in the parentheses to a string. I updated the answer with output. – rndm Apr 18 '14 at 18:35
  • I am not sure why do you have to it this way ...SLOT is a macro "They are examined by the preprocessor before actual compilation of code begins and before any code is actually generated by regular statements" I don't think you will be able to call a macro from inside a string ...why not just function pointer instead of F being a string?! – Samer Apr 18 '14 at 18:45
  • There's a selection of slots in a dialog, and after one is selected it returns a string. The only way I can use function pointers after is to check for every single return value and use connect with function pointer for that value. – rndm Apr 18 '14 at 18:49

1 Answers1

4

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).

serg.v.gusev
  • 501
  • 4
  • 13
  • 1
    This answer leaks pointers, namely: QPushButton *b = new QPushButton("pressme"); is not getting a parent, and the Test class is not having a parent either, nor smart pointers. – László Papp Apr 19 '14 at 02:09
  • @Ipapp You can gladly add the missing parts though I have to say that while incomplete (the author never mentions that he provides a fully working example) it illustrates how things work in regards to what the OP is asking. – rbaleksandar Nov 15 '16 at 08:40