I want to declare a global property in a config file and use it in other files. for example declare mainbg
in:
Style.qml:
Adding some contribute to @pixelgrease answer, I found another technique that doesn't require the path relative import "."
, workarounding the bug QTBUG-34418. This is useful especially if one has qmldir
and singleton class in a different place than the qml file where the singleton is used. The technique requires defining a proper module inside the tree structure: the module is then resolved by adding the parent path of the module to the QML engine with QmlEngine::addImportPath(moduleParentPath)
. For example:
qml/
├── /
│ ├── .qml
│ ├── qmldir
In main.cpp you have then:
QQmlApplicationEngine engine;
engine.addImportPath("qrc:/qml"); // Can be any directory
engine.load("qrc:/qml/main.qml");
If you use resources, qml.qrc:
(...)
qml/main.qml
qml/MySingletons/MySingleton.qml
qml/MySingletons/qmldir
In qmldir:
module MySingletons
singleton MySingleton 1.0 MySingleton.qml
In main.qml, or any other qml file in a different directory:
import MySingletons 1.0
Then you use MySingleton class as usual. I attached the example MySingletonWithModule.7z to bug QTBUG-34418 for reference.