Passing c++ pointers to a QQuickItem subclass created in QML
-
I need the c++ side of some custom QQuickItem subclasses to know about other objects on the c++ side that are not in QML and be able to have pointers to those objects. If I was constructing these QQuickItem objects in C++, I could simply pass in pointers via a member function or a constructor, but instead these are getting instantiated in QML. Once created, how can I then pass these pointers in? I can easily call C++ methods on these objects from QML, but QML doesn't have the other c++ pointers that need to be passed because they only exist in C++. Even if I need to somehow make sure all instances of a QQuickItem subclass have automatic access to a C++ singleton, that would be fine, but I have no idea how to do this with QML is solely responsible for dynamically creating and destroying these QQuickItems.
Help!
-
You can pass them as root context to the QML engine, or - better - create a QML singleton: "link":http://qt-project.org/doc/qt-5/qtqml-cppintegration-definetypes.html#registering-singleton-objects-with-a-singleton-type.
-
Ok, would this be considered an acceptable approach:
I have a C++ pointer -- I expose this pointer to the rootcontext similar to:
@....setContextProperty("_cppLink",linkData);@
Here, QML will see _cppLink which will actually be a C++ pointer called linkData.
Now, I have a Q_INVOKABLE on a custom different QQuickItem subclass
that can accept a c++ pointer of my object type:@Q_INVOKABLE void givePointer(Link* link){...@
Now, in QML, after creating an instance of my different QQuickItem subclass, I do this
from inside that new instance:@MyQMLInstance{
Component.onCompleted{
....givePointer(_cppLink)@Is this the proper way of making connections between different c++ objects, but doing
so from the QML side? Note that QML doesn't actually need to do anything with this pointer,
except just pass it to another object, which uses it exclusively from the c++ side. -
Yeah, that sounds about right and should work. It is better to use QML Singleton than a root context property (singletons are better optimised by the QML engine).
Since this looks like a singleton, though, maybe you can make it a singleton in C++, and skip the whole hassle of going through QML. I don't like Singletons all that much myself, but this seems to be a good place to use one.
-
I don't like singletons either and I don't think they would be necessary here; QML has no reason to actually use the data other than pass it off to another c++ object, which happens infrequently, therefore I wouldn't expect any gains from the QML Engine's optimization on a QML singleton. Nor do I see a need to make it a singleton on the c++ side; it's simply a single object that is exposed. The object is in the same scope as the QML engine itself (created in main.cpp) so there is no risk of it getting deleted as long as the program is alive.