在 QML 中动态更改材质主题



在QML中处理主题更改的最佳方法是什么? 我注意到一些控件(如 Switch 和 ApplicationWindow(会自动执行此操作,但其他控件(如文本和矩形(则不会!

是否有可能避免检查当前设置的主题,然后每次都相应地设置颜色?(color: theme.position < 1 ? "black" : "white"(

主.qml

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Controls.Material 2.13
//ok:  the background color changes automatically when the theme changes
ApplicationWindow {
id: root
visible: true
width: 1366
height: 768
title: qsTr("Theme")
Material.theme: theme.position < 1 ? Material.Light : Material.Dark
//ok:  the text color changes automatically when the theme changes
Switch {
id: theme
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 10
text: "Dark theme"
checked: false
}
//not ok: the background is always white
Rectangle {
anchors.centerIn: parent
width: 200
height: width
//not ok: the color is always black
Text {
anchors.centerIn: parent
text: "some text"
font.pixelSize: 40
}
}
}

qtquickcontrols2.conf

[Controls]
Style=Material
[Material]
Theme=Dark
Accent=Orange
Primary=BlueGrey

TextRectangle是Qt Quick的原语,这意味着它们不理解Qt Quick Controls的材质样式颜色传播。您可以改用LabelFrame

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Controls.Material 2.13
ApplicationWindow {
id: root
visible: true
width: 1366
height: 768
title: qsTr("Theme")
Material.theme: theme.position < 1 ? Material.Light : Material.Dark
Switch {
id: theme
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 10
text: "Dark theme"
checked: false
}
Frame {
anchors.centerIn: parent
width: 200
height: width
Label {
anchors.centerIn: parent
text: "some text"
font.pixelSize: 40
}
}
}

请注意,Frame将使用鼠标事件,因此如果您不希望这样做,则需要使用 例如Control,并使用材质样式的附加属性自行处理颜色:

Control {
anchors.centerIn: parent
width: 200
height: width
background: Rectangle {
color: parent.Material.background
border.color: parent.Material.foreground
}
Label {
anchors.centerIn: parent
text: "some text"
font.pixelSize: 40
}
}

最新更新