scdmb scdmb - 3 months ago 21
C++ Question

What is the difference between a slot and a method in Qt?

What is the difference between a slot (a method declared in

slots
section) and a method in Qt (a method declared with Q_INVOKABLE keyword)? They both can be invoked using
QMetaObject::invokeMethod
, they are both accepted when connecting to a slot using
SLOT
macro, however when getting type of metamethod it can be returned either
QMetaMethod::Method
or
QMetaMethod::Slot
, so it seems that there is some difference for Qt?

Answer

The only difference is whether the method is listed as a slot or as not-a-slot in the class's metadata. In both Qt 4 and Qt 5, connection to either a slot or an invokable succeeds:

#include <QObject>
struct Test : public QObject {
  Q_SLOT void slot() {}
  Q_INVOKABLE void invokable() {}
  Q_OBJECT
};

int main() {
  Test test;
  auto c1 = QObject::connect(&test, SIGNAL(destroyed(QObject*)), &test, SLOT(slot()));
  auto c2 = QObject::connect(&test, SIGNAL(destroyed(QObject*)), &test, SLOT(invokable()));
  Q_ASSERT(c1);
  Q_ASSERT(c2);
}
#include "main.moc"

It's up to the user to decide how the difference between a slot and an invokable is interpreted. E.g. if you're exposing the slot list to the user in some way, you won't be exposing the invokable method list unless you choose to do so.