ReferenceError to root window id when creating QML from C++
-
I want to load QML files from within C++.
The problem is that the main window cannot be referenced by id from a different QML file.
I create the main window first:QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); QQuickWindow *window = qobject_cast<QQuickWindow*>(engine.rootObjects().at(0)); if (!window) { qFatal("Error: Your root item has to be a window."); return; } window->show(); root = window->contentItem();
main.qml:
import QtQuick 2.12 import QtQuick.Window 2.12 Window { id: root width: 640 height: 480 }
Then, I add a rectangle:
QQmlComponent component(enginePtr, QUrl("qrc:/rec.qml")); QQuickItem* object = qobject_cast<QQuickItem*>(component.beginCreate(enginePtr->rootContext())); if(object == nullptr) return; QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership); object->setParentItem(root); object->setParent(enginePtr); component.completeCreate();
rec.qml:
import QtQuick 2.0 Rectangle { width:100 color:"red" Component.onCompleted: { height = root.height/Math.max(sourceSize.height, sourceSize.width) * scale; } }
As you can see, rectangle height is calculated from root.height, which is MainWindow height. But, this results in the error:
ReferenceError: root is not defined
How can I refer to the properties of the main window from a different QML file?
-
Do you have a specific reason doing all that in C++?
It's considered bad practice. -
@GrecKo said in ReferenceError to root window id when creating QML from C++:
It's considered bad practice.
what? why?
@ChrisTof said in ReferenceError to root window id when creating QML from C++:
QQuickItem* object = qobject_cast<QQuickItem*>(component.beginCreate(enginePtr->rootContext()));
you should use the context (or a child context) of the root item, rather the engine's rootContext
QQmlContext* rootItemContext = QQmlEngine::contextForObject(root);
-
@raven-worx said in ReferenceError to root window id when creating QML from C++:
what? why?
Instead of paraphrasing, I'll copy those links:
-
@GrecKo
Yes, I have reasons to do all of that in C++. Even more, I have no choice.@raven-worx
Thank you very much! That is what I needed. In my case, I have to refer to the window variable:QQmlContext* rootItemContext = QQmlEngine::contextForObject(window); QQuickItem *object = qobject_cast<QQuickItem*>(component.beginCreate(rootItemContext))