12.7.  invokeMethod()

[ fromfile: invokemethod.xml id: invokemethod ]

Qt's capability to connect signals to slots requires a mechanism to indirectly call the slots in a type-safe way, by name. When a slot is called, it is actually done by invokeMethod(). Example 12.16 shows how it accepts a string for the method name. In addition to slots, regular methods marked Q_INVOKABLE can be invoked indirectly this way.

Example 12.16. src/reflection/invokemethod/autosaver.cpp

void AutoSaver::saveIfNecessary() {
    if (!QMetaObject::invokeMethod(parent(), "save")) {
        qWarning() << "AutoSaver: error invoking save() on parent";
    }
}

Similar to QObject::connect(), invokeMethod() takes an optional argument, the Qt::ConnectionType, which enables you to decide if you want synchronous or asynchronous invocation. The default, Qt::AutoConnection, executes the slot synchronously when the sender and receiver are in the same thread.

To pass typed arguments to a function via invokeMethod(), you can create values with the Q_ARG macro Example 12.17, which returns a QGenericArgument, encapsulating type and value information for a single argument.

Example 12.17. src/reflection/invokemethod/arguments.cpp

QByteArray buffer= ... ;
const bool b = QMetaObject::invokeMethod(m_thread, "calculateSpectrum",
                  Qt::AutoConnection,
                  Q_ARG(QByteArray, buffer),
                  Q_ARG(int, format.frequency()),
                  Q_ARG(int, bytesPerSample));