Important: Please read the Qt Code of Conduct -

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.


  • Thank you for your answer.

    What if I want to call this function asynchronously?

    I tried to call this function asynchronously in C++, but it failed.


Log in to reply