Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
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?
See QObject's "property()":http://qt-project.org/doc/qt-5/qobject.html#property and "setProperty()":http://qt-project.org/doc/qt-5/qobject.html#setProperty, as well as QMetaObject's "invokeMethod()":http://qt-project.org/doc/qt-5/qmetaobject.html#invokeMethod.
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.
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.
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:
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?