gpt4 book ai didi

qt - 在 QML 中动态更改 Material 主题

转载 作者:行者123 更新时间:2023-12-04 10:55:55 27 4
gpt4 key购买 nike

在 QML 中处理主题变化的最佳方式是什么?我注意到一些控件(如 Switch 和 ApplicationWindow)会自动执行此操作,但其他控件(如 Text 和 Rectangle)则不会!

是否有可能避免每次都检查当前设置的主题然后相应地设置颜色? (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 的 Material 样式颜色传播。您可以改用 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 will consume mouse events ,所以如果你不想那样,你需要使用例如控制,并使用 Material 样式的附加属性自行处理颜色:

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
}
}

关于qt - 在 QML 中动态更改 Material 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59196695/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com