Search code examples
c++qtqmlqtquick2qtcore

QMetaObject::invokeMethod fails to invoke a QML/JS function


This looks to be a by-the-book simple thing to do, but for some mysterious to me reason fails.

Flickable {
    objectName: "flickable"

    function gotoXY(x, y) {
        ...
    }
}

C++

QMetaObject::invokeMethod(flickable, "gotoXY", Q_ARG(qreal, pos.x()), Q_ARG(qreal, pos.y()));

flickable is a QObject* and is indeed verified to be the appropriate object by outputting its objectName. But the method cannot be found:

QMetaObject::invokeMethod: No such method QQuickFlickable_QML_1::gotoXY(qreal,qreal)

Any ideas why?


Solution

  • Replace qreal with QVariant, so write something like this:

    QMetaObject::invokeMethod(flickable, "gotoXY",
                              Q_ARG(QVariant, pos.x()),
                              Q_ARG(QVariant, pos.y()));
    

    The reason is that JS arguments like that are interpreted as QVariant with QML. Javascript is not a strongly typed language, so there is no direct mapping between C++ types (even registered) and javascript as such.