I want to expose a global variable from C++ to QML, but I'm not able to make it accessible for all QML files.
I'm trying to add my context property to the QQmlEngine
root context because, according to the documentation:
QQmlEngine documentation:
QQmlContext * QQmlEngine::rootContext() const Returns the engine's root context.
The root context is automatically created by the QQmlEngine. Data that should be available to all QML component instances instantiated by the engine should be put in the root context.
Additional data that should only be available to a subset of component instances should be added to sub-contexts parented to the root context.
It's supposed that this property should be available for all the QML files. I'm doing it like that:
MainWindow.cpp
MainWindow::MainWindow(QObject *parent)
: QObject(parent),
engine(new QQmlEngine(parent)),
window(NULL)
{
// Set global properties
this->setIndependentResolutionScale();
// Load the QML file
QQmlComponent component(this->engine, QUrl("qrc:/qml/MainWindow.qml"));
this->window = qobject_cast<QQuickWindow *>(component.create());
this->engine->setIncubationController(this->window->incubationController());
}
void MainWindow::setIndependentResolutionScale()
{
// In a standard resolution laptop screen->logicalDotsPerInch() is 72
QScreen *screen = qApp->screens().at(0);
qreal u = 72.0/screen->logicalDotsPerInch();
this->engine->rootContext()->setContextProperty("u", u);
}
I haven't got problems if I use this property in MainWindow.qml
but, if I try to use it in other QML file I get a ReferenceError: u is not defined
.
Why is this error caused? Is it because QQmlEngine
is not unique? Is there another way to create a global variable?
I'm using Qt 5.2