Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Calling anonymous QML functions from C++

Calling anonymous QML functions from C++

Scheduled Pinned Locked Moved General and Desktop
3 Posts 3 Posters 4.4k Views
  • 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.
  • M Offline
    M Offline
    manuelsch
    wrote on 16 Mar 2011, 23:11 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
    • G Offline
      G Offline
      Globinette
      wrote on 26 Jul 2013, 09:29 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 18 Jan 2019, 09:20 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 Extensions
        • Unsolved