QT SLOT: pointer to member function error

I am currently working on a Qt project and I have problems with SLOT. I want to pass a pointer to a member function as an argument to SLOT. For this, I declared SLOT in my class, but when I do this, I get a MOC error. I do not know if what I want to achieve is possible.

An example syntax for a class named MainFrame:

void slotAnswerReceived (QString answer, void (MainFrame::*ptr)(QString));

I have no connection anywhere, nothing of this function, and the only error I have is on this line above.

Thank you all for your help. I cannot find any solution on the Internet (but I found this article explaining SIGNAL and SLOT in depth if anyone is interested).

+4
source share
1 answer
  • Declare a typedef for this type of member pointer.

  • Declare and register a metatype for this typedef.

  • Use only typedef - remember that moc uses string comparisons to determine type equality; it does not have a parser for an expression of type C ++.

The following is an example. At the time of the call a.exec(), there are two events in the event queue QMetaCallEvent. The first - c.callSlot, the second - a.quit. They are performed in order. Recall that a call in the queue (regardless of whether invokeMethodor because of signal activation) leads to publication QMetaCallEventfor each recipient.

#include <QCoreApplication>
#include <QDebug>
#include <QMetaObject>

class Class : public QObject {
   Q_OBJECT
public:
   typedef void (Class::*Method)(const QString &);
private:
   void method(const QString & text) { qDebug() << text; }
   Q_SLOT void callSlot(const QString & text, Class::Method method) {
      (this->*method)(text);
   }
   Q_SIGNAL void callSignal(const QString & text, Class::Method method);
public:
   Class() {
      connect(this, SIGNAL(callSignal(QString,Class::Method)),
              SLOT(callSlot(QString,Class::Method)),
              Qt::QueuedConnection);
      emit callSignal("Hello", &Class::method);
   }
};
Q_DECLARE_METATYPE(Class::Method)

int main(int argc, char *argv[])
{
   qRegisterMetaType<Class::Method>();
   QCoreApplication a(argc, argv);
   Class c;
   QMetaObject::invokeMethod(&a, "quit", Qt::QueuedConnection);
   return a.exec();
}

#include "main.moc"
+7
source

Source: https://habr.com/ru/post/1533145/


All Articles