我正在使用 Fusion 风格开发 QML 应用程序。我正在使用 Qt 5.15 lts。
我想制作一个在运行时切换颜色主题(浅色模式、深色模式等)的功能。
文档说可以通过修改QML中的
palette
对象来更改融合样式的颜色系统。ApplicationWindow
类型很容易完成,但我必须使用我的自定义 Window
对象,而不是 ApplicationWindow
。// @theme_dark_ and @theme_light_ are pre-defined palette object.
Q_INVOKABLE void Backend::SetDarkMode(const bool flag) {
qGuiApp->setPalette(flag ? theme_dark_ : theme_light_);
}
我在启动 QML 应用程序之前检查了
setPalette
方法是否有效(QGuiApplication::exec
),但在 QML 应用程序运行时却不起作用。palette
类型中的Window
,或者在QML应用程序运行时调用QCoreApplication::setPalette
?在下面的示例中,我有一个
Page
组件,我可以在其中设置 palette
,该组件将由其所有子组件继承:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
palette: AppPalettes.current
title: "Palette Demo"
Flickable {
id: flickable
anchors.fill: parent
contentWidth: columnLayout.width
contentHeight: columnLayout.height
clip: true
ScrollBar.vertical: ScrollBar {
width: 20
policy: ScrollBar.AlwaysOn
}
ColumnLayout {
id: columnLayout
width: flickable.width - 40
CheckBox {
id: darkMode
text: checked ? qsTr("Dark Mode") : qsTr("Light Mode")
checked: AppPalettes.darkMode
onToggled: AppPalettes.darkMode = checked
}
Label { text: qsTr("Sample Label") }
CheckBox { text: qsTr("Sample CheckBox") }
RadioButton { text: qsTr("Sample Radio Button") }
Button { text: qsTr("Sample Button") }
ComboBox {
Layout.preferredWidth: 200
model: [ "ComboValue 1", "ComboValue 2", "ComboValue 3" ]
}
Slider { from: 0; to: 100 }
ListView {
model: 20
Layout.preferredHeight: contentHeight
delegate: ItemDelegate {
text: "ListItem " + (index + 1)
onClicked: ListView.view.currentIndex = index
}
}
}
}
}
// qmldir
singleton AppPalettes 1.0 AppPalettes.qml
// AppPalettes.qml
pragma Singleton
import QtQuick
AppPalettesPrivate { }
// AppPalettesPrivate.qml
import QtQuick
import QtQuick.Controls
QtObject {
property bool darkMode: true
readonly property Palette current: darkMode ? dark : light
readonly property Palette dark: Palette {
alternateBase: "#000"
base: "#000"
button: "#111"
buttonText: "#fff"
dark: "#666"
highlight: "#d73"
highlightedText: "#000"
light: "#000"
mid: "#444"
midlight: "#333"
placeholderText: "#80000000"
shadow: "#888"
text: "#fff"
window: "#222"
windowText: "#fff"
}
readonly property Palette light: Palette {
alternateBase: "#fff"
base: "#fff"
button: "#eee"
buttonText: "#000"
dark: "#999"
highlight: "#38c"
highlightedText: "#fff"
light: "#fff"
mid: "#bbb"
midlight: "#ccc"
placeholderText: "#80000000"
shadow: "#777"
text: "#000"
window: "#eee"
windowText: "#000"
}
}
您可以在线尝试!