Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt
  • Unsolved
Collapse
qtws26_logo

The Qt Event of the Year: Qt World Summit 2026

Save Your Spot >
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Calling anonymous QML functions from C++
Qt 6.12 LTS is out! See what's new in the release blog

Calling anonymous QML functions from C++

Scheduled Pinned Locked Moved General and Desktop
3 Posts 3 Posters 5.0k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • ? Offline
    ? Offline
    A Former User
    wrote on last edited by
    #1

    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":http://comments.gmane.org/gmane.comp.lib.qt.qml/1820 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?

    Cheers,

    Manuel

    EDIT: spelling

    1 Reply Last reply
    0
    • ? Offline
      ? Offline
      A Former User
      wrote on last edited by
      #2

      Hi,

      As of Qt 5.0, it is possible to solve this with "QJSValue":http://qt-project.org/doc/qt-5.1/qtqml/qjsvalue.html .

      C++ :

      @class Foo : public QObject
      {
      Q_OBJECT

      public :
          Q_INVOKABLE void bar(QJSValue function)
          {
              function.call(QJSValueList() << 42);
          }
      

      };@

      QML :

      @Foo.bar(function(result) {
      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.

      Cheers

      1 Reply Last reply
      0
      • P Offline
        P Offline
        pascal0000
        wrote on last edited by
        #3

        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.

        Cheers

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt
        • Unsolved