How to use pragma Singleton?
-
I created a ThemeManager.qml to manage my theme.qml. But I can't use pragma Singleton in theme.qml. I won't be able to find the relevant properties.
ThemeManager.qml
import QtQuick 2.0 QtObject { property QtObject lightTheme: LightTheme property QtObject darkTheme: DarkTheme property QtObject currentTheme: lightTheme function setTheme(theme) { if (theme === "light") { currentTheme = lightTheme } else if (theme === "dark") { currentTheme = darkTheme } } }
LightTheme.qml
pragma Singleton import QtQuick 2.0 QtObject { readonly property color textColor: "#000000" readonly property color backgroundColor: "#ffffff" }
DarkTheme.qml
pragma Singleton import QtQuick 2.0 QtObject { readonly property color textColor: "#ffffff" readonly property color backgroundColor: "#000000" }
Main.qml
import QtQuick import QtQuick.Window import QtQuick.Controls Window { visible: true width: 640 height: 480 property alias themeManager: themeManager ThemeManager { id: themeManager } Text { text: "Hello, world!" color: themeManager.currentTheme.textColor anchors.centerIn: parent } MouseArea { anchors.fill: parent onClicked: { themeManager.setTheme( themeManager.currentTheme === themeManager.lightTheme ? "dark" : "light") } } }
-
I wasn't able to get it to work with singleton, but I did get a theme swap to work that could be a globally accessible property of a root page (though I'm just doing it in one main.qml).
Here's the sample project with all the source.
---
ThemeManager.qml
-----------import QtQuick QtObject { id: mgr property Loader loader: Loader { source: "BlueTheme.qml" } property QtObject theme: loader.item function swap() { if (loader.source == "BlueTheme.qml") { loader.source = "GreenTheme.qml" } else { loader.source = "BlueTheme.qml" } } }
---
main.qml
-----------import QtQuick import QtQuick.Layouts import QtQuick.Controls Window { id: window width: 500 height: 300 visible: true title: qsTr("Qt 6.5 QML Theme Swap") ThemeManager{ id: tm } Rectangle { anchors.fill: parent color: tm.theme.aColor Button { id: theButton text: "swap" anchors.centerIn: parent onClicked: tm.swap() } } }
-
@christofer said in How to use pragma Singleton?:
@jeremy_k I'm using
pragma singleton
with Qt 6.5 without a qmldir file. For example, this hasMyConstants.qml
in the Base module.That's great. Perhaps you can explain what was required, for the edification of the OP and future readers.
-
@jeremy_k
Here you go. Note that I didn't use a qmldir file.// MyConstants.qml pragma Singleton import QtQuick QtObject { readonly property int aNumber: 13 readonly property color aColor: "teal" readonly property string someWords: "Words from MyConstants." }
//main.qml Window { color: MyConstants.aColor }
But to see how it is wired together you need to see a whole project imho.
-
In case it helps. I minimized the example app to just the pragma Singleton stuff.
https://gitlab.com/christoferjennings/qt-6-5-modules-sandbox/-/tree/just-pragma-singleton