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

标签 qt qml material-design

在 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/

相关文章:

c++ - 如何让 QModelIndex 在 QAbstractTableModel 中插入新行?

qt - PyQt:使用 alpha channel 而不是预乘颜色 channel 创建 QPixmap

c++ - Blackberry 10 Cascades 中的布局有问题,qml(C++ 和 QT)

python - 代码中的 QML ListView 部分

Angular Material 7 mat-sidenav 样式底层元素

android - 共享过渡动画故障

c++ - 将字符串设置为 QDoubleSpinBox

qt - Qt中如何判断文件是照片还是视频?

c++ - 我应该如何在 Qt 中构建我的 GUI?

android - ( Material )EditText下划线颜色