Get rootContext from within QQuickItem
-
Can I retrieve the root context from within a QQuickItem?
I need the root context in order to make one of my QQuickItem subclass members accessible from QML. From within a QQuickView object I can just do this:rootContext()->setContextProperty("camera", m_camera);But QQuickItem has no rootContext() method. Another post claimed that root context can be accessed from any QObject like this:
QQmlContext *context = qmlEngine(this)->rootContext()However when I invoke that from my QQuickItem subclass constructor, qmlEngine() return nullptr. Moreover I can't find any documentation for method QObject::qmlEngine().
Does anyone know the proper way to do this?
Thanks
-
I think you're mixing 2 ideas: context properties and visual objects.
QQuickItem is a visual object, like
Rectangle,Buttonetc. It makes no sense to have it as a context property!Root context properties are never drawn on screen - they only provide property data to other (visible) QML items.
So, if you need to expose some data to QML - use
QObjectand set it as context property. If you want to add a custom visual element to your QML scene - useQQuickItemand register is usingqmlRegisterType(). -
Thanks @sierdzio . My visual object (the QQuickItem) contains a QObject subclass instance m_camera (not a visual object), which is what I want to expose as a property to QML. How do I expose m_camera object to qml from within my QQuickItem subclass code? I need the root context in order to do that, right?
Thanks!
-
Thanks @sierdzio . My visual object (the QQuickItem) contains a QObject subclass instance m_camera (not a visual object), which is what I want to expose as a property to QML. How do I expose m_camera object to qml from within my QQuickItem subclass code? I need the root context in order to do that, right?
Thanks!
@Tom-asso said in Get rootContext from within QQuickItem:
Thanks @sierdzio . My visual object (the QQuickItem) contains a QObject subclass instance m_camera (not a visual object), which is what I want to expose as a property to QML. How do I expose m_camera object to qml from within my QQuickItem subclass code? I need the root context in order to do that, right?
No, just add a property in your QQuickItem, like this:
class YourItem : public QQuickItem { Q_OBJECT Q_PROPERTY(ClassName* camera READ camera CONSTANT) public: ClassName* camera() const { return m_camera; } };Then you can use it in QML as a normal property of an object:
YourItem { id: item anchors.fill: parent } Text { text: qsTr("Camera object is: " + item.camera) }