Newbie : pass C++ instances to QML
-
Hello,
I would like to know if it is possible to instantiate an object in C++ (which exposes properties with Q_PROPERTY) and to use this object instantiated in C++ in a QML context.
I know that to use a C++ object in QML, I have to use qmlRegisterType but I don't want to do instantiation in QML.
Thanks for your help
sc
-
@sebastienc hi
here is an overview of QML / c++ integration methods
looks like you need this one -
@sebastienc sure
in your particular case:
https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonInstance -
Thank you, it seems to suit my needs.
Is there an equivalent with qt 5.11 as this method was introduced in qt 5.14 ?
-
@sebastienc For older Qt, I think this is what you need:
qmlEngine->rootContext()->setContextProperty("myobj", myCppObjInstance);
Your object will be accessible via the global
myobj
property (or whatever you want to call it) in your QML.Obviously, your C++ object has to be a
QObject
and have QML-compatible members exposed on it (e.g.Q_INVOKABLE
methods and/orQ_PROPERTY
members) to be useful.