QML global variable
-
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 aReferenceError: 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
-
I created global variables using a class with static fields. For example, C++ header code:
@class Global: public QObject
Q_PROPERTY(int var1 READ getVar1 WRITE setVar1 NOTIFY signalVar1Changed)
public:
static int getVar1() { return _var1; }
static void setVar1(int v) { _var1 = v; emit signalVar1Changed; }
private:
static int _var1 = 0;
}@
Then you should make class Global available from QML.
QML code:
@Item {
...
someProperty = g.var1;
...
Global {
id: g
}
}@