Custom QQuickItem -- accessing QML functions from c++



  • Accessing C++ functions in a subclassed QQuickItem from the QML side is easy via Q_INVOKABLE but what if I want to go in reverse and call QML functions from c++? I've seen several examples that require finding the QML object first so you know what object to call on, but that would only seem necessary if a different c++ object is calling functions in the QML -- but since the C++ object of a QQuickItem is the same C++ object as the QML object, what is the easy way to get Q_INVOKABLE style communication going, but in the other direction so my C++ can access QML functions and properties?


  • Moderators



  • I've used invokeMethod before but it requires you pass in the object you are calling the method on. This makes sense if you are invoking a QML method on an object that is separate from the calling C++ code. But what if the QML method you are invoking is in the QML part of the C++ QQuickItem? What do you pass to invokeMethod() to indicate you are using the "this" object? I can't find any information in the docs about this seemingly straightforward task.


  • Moderators

    You have pretty much answered yourself: pass this as the object :)



  • Well of course I tried that. It does not work. invokeMethod has no overload for the custom type that this represents and that is what the compiler reports.


  • Moderators

    You must be doing something wrong. QQuickItem is derived from QObject: it has to work, and actually does work, I use it all over the place in one of my projects.

    If it really fails, try casting the pointer (qobject_cast). But that should really not be necessary.



  • I got it to work by simply doing this:

    QObject*t=this;

    This essentially casts it and I can then pass t as the the object. Wise? It is working now and I can call the QML function in this way.

    There appears to be no other way to directly pass a custom class to invokeMethod. I agree that it shouldn't make a difference since my this class derives from QQuickItem which derives from QObject. I wonder what is going on?


Log in to reply
 

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