Calling anonymous QML functions from C++

  • Hi,

    I found out, that you can call QML functions from C++ using
    QMetaObject::invokeMethod(object, "myQmlFunction",
    Q_RETURN_ARG(QVariant, returnedValue),
    Q_ARG(QVariant, msg));
    But that does not work with anonymous QML functions that are passed as an argument to a C++ function, because it has no name.
    There is an idea as a workaround "found in a mailing list": that uses signals to make this work.
    I think this is somewhat cumbersome and I'd like to make the QML developer be able to use "the natural way".

    Is there any possibility to solve this issue without signals?



    EDIT: spelling

  • Hi,

    As of Qt 5.0, it is possible to solve this with "QJSValue": .

    C++ :

    @class Foo : public QObject

    public :
        Q_INVOKABLE void bar(QJSValue function)
   << 42);


    QML : {
    console.log('returned ', result, ' from c++')

    will output 'returned 42 from c++'

    You can also do all sorts of checks on the object passed to the c++ function. In this case, you might want to call "isCallable" to make sure the object is a function.


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.