QtOnAndroid

Qt Signals

Qt Widget Hierarchy | | Qt Signal-Slot Example

Qt features its own way of reflection resp. introspection as an extension of the C++ standard. The extensions are handles by the so called MOC, the meta object compiler.

This means that any class that is derived from QObject, can declare methods to be availabe to introspection via the “slots” keyword. Those slots can be invoked via QMetaObject::invokeMethod(object, “methodname”).

class DerivedObject1: public QObject
{
public:

   DerivedObject1(QObject *parent = NULL)
      : QObject(parent)
   {}

public slots:

   void slot()
   {
      std::cout << "slot called" << std::endl;
   }

};

Invocation of the above slot:

DerivedObject1 *d = new DerivedObject1;
QMetaObject::invokeMethod(d, "slot");

Qt also allows the automatic invocation of a slot, if a particular signal occurred. Signals are declared with the “signal” keyword and triggered with the “emit” keyword:

class DerivedObject2: public QObject
{
public:

   DerivedObject2(QObject *parent = NULL)
      : QObject(parent)
   {}

signals:

   void signal();

public:

   void trigger()
   {
      emit signal();
   }

};

In order to let a slot react automatically on a signal, both need to be connected:

DerivedObject1 *d1 = new DerivedObject1;
DerivedObject2 *d2 = new DerivedObject2;
QObject::connect(d2, SIGNAL(signal()), d1, SLOT(slot());

When the signal is triggered, then all connected slots are called:

d2->trigger()
→ “slot called”

There is no limitation on the number of connected slots for a particular signal. The connections can be changed at run-time. They are also thread-safe by default. This allows for simple inter-thread message passing.

Qt Widget Hierarchy | | Qt Signal-Slot Example

Options: