Qml Shared Style
-
In my application I use a Qml Menu as a context menu in various places. I have created a MenuStyle that I would like to use on all of them without having to copy the style to each of them. I found the Qml Styling page https://wiki.qt.io/Qml_Styling. It seems to be close to what I want, but not quite.
Style.qml
pragma Singleton import QtQuick 2.4 import QtQuick.Controls 1.4 import QtQuick.Controls.Styles 1.4 MenuStyle { id: contextMenuStyle frame: Rectangle { color: "gray" } itemDelegate.label: Label { anchors.horizontalCenter: parent.horizontalCenter color: "white" text: styleData.text } itemDelegate.background: Rectangle { color: styleData.selected ? "blue" : "gray" } }
Test.qml
Menu { id: contextMenu style: MyStyle.contextMenuStyle; MenuItem { text: qsTr('Test') } }
main.cpp
qmlRegisterSingletonType(QUrl("file:///Qml/Style.qml"), "net.test.com", 1, 0, "MyStyle" );
Can this be done this way or is there a better way?
-
I don't know if it can be done exactly like that, but the problem with that approach is you can only have one style in your Style.qml. My Style.qml typically has a QtObject as the root object, and properies within it for each property.
pragma Singleton import QtQuick 2.3 import QtQuick.Controls.Styles 1.1 QtObject { property QtObject color: QtObject { readonly property color background: "#eeeeee" readonly property color button: "#60aabac5" } property var buttonStyle: Component { ButtonStyle { } } main.qml: Button { color: Style.color.button style: Style.buttonStyle }
...and you can put declare the singleton in your qmldir file, you don't have to write code to register it.
-
qmlRegisterSingletonType(QUrl("file:///Qml/Style.qml"), "net.test.com", 1, 0, "MyStyle" );
The first parameter
uri
is the one which you will use as an import in QML.
Check this example. -
@xargs1 You have done the style this way before and it worked?
I switched to this and it is still not working. Not sure if the qmldir is setup right.
My directory structure looks like this
- absolute
| + Qml
| | + qmldir
| | + Style.qml
| | + MainWindow.qml
| | + main.qml
Style.qml
pragma Singleton import QtQuick 2.4 import QtQuick.Controls 1.4 import QtQuick.Controls.Styles 1.4 QtObject { property var contextMenuStyle: Component { MenuStyle { frame: Rectangle { color: "gray" } itemDelegate.label: Label { anchors.horizontalCenter: parent.horizontalCenter color: "white" text: styleData.text } itemDelegate.background: Rectangle { color: styleData.selected ? "blue" : "gray" } } } }
MainWindow.qml
Menu { id: contextMenu style: MyStyle.contextMenuStyle; MenuItem { text: qsTr('Test') } }
qmldir
singleton MyStyle 1.0 Style.qml
- absolute