How are y'all making global variables in QML
-
wrote 22 days ago last edited by MaximBozek 5 Dec 2025, 14:48
Hi
I want to use certain QML (property) variables in multiple QML files, but don't really know how to integrate this into my project. I have a C++ and QML project in Qt 6.3
Anyone have a good workflow for this?
-
Usually, I keep read-only globals around in JavaScript file.
Something like// myGlobalVariables.js var defaultUrl = "https://www.qt.io"
...and import it and use it, where needed
// import whatever import "myGlobalVariables.js" as RootEnv ApplicationWindow { visible: true title: "Enter Url" TextEdit { anchors.centerIn: parent text: RootEnv.defaultUrl } }
If globals should be writable, I usually use a singleton.
-
Usually, I keep read-only globals around in JavaScript file.
Something like// myGlobalVariables.js var defaultUrl = "https://www.qt.io"
...and import it and use it, where needed
// import whatever import "myGlobalVariables.js" as RootEnv ApplicationWindow { visible: true title: "Enter Url" TextEdit { anchors.centerIn: parent text: RootEnv.defaultUrl } }
If globals should be writable, I usually use a singleton.
@Axel-Spoerl Both options let my skin crawl!
But I recently learned that using context property is significantly worse than these. Due too lookup times.
"You can and you can't,
You shall and you shan't,
You will and you won't,
And you will be damned if you do,
And you will be damned if you don't." -
Singleton is the way.
-
I agree that Singleton is the way.
But it really depends on the complexity of your app.
When I have 2-3 qml files and need globals, I really don't want to keep a singleton around. -
A QML singleton file is hardly more complicated and has the benefit of being typed and using a proper module import, making the tooling easy.
// Globals.qml pragma singleton import QtQml QtObject { readonly property string defaultUrl: "https://www.qt.io" }
1/6