首页 > 解决方案 > 设置应用程序以记住主题:深色与浅色

问题描述

有这个 QML 设置来记住应用程序主题:

import QtQuick.Controls 2.0 as QQC2

QQC2.ApplicationWindow {

    id: standaloneWindow // ID is required to be able to get properties
    
    Material.theme: Material.Dark // Can be either Dark or Light

    Component.onCompleted: {
        // On launch, read theme from settings file
        standaloneWindow.Material.theme = appSettings.materialTheme
    }

    Component.onDestruction:{
        // On close, write theme to settings file
        appSettings.materialTheme = standaloneWindow.Material.theme
    }

    Settings {
        id: appSettings

        category: "Theme"
        property int materialTheme // Store theme as "int" type in settings file
    }

}

问题

在第一次启动时(例如删除设置文件时),主题无法以Dark. 在第一次启动时,应用程序总是Light主题开头,无论如何!

原因

当没有设置文件时,appSettings.materialTheme成为0默认int类型。因此,0等价于Material.Dark枚举。这就是为什么在没有设置文件时应用程序总是以暗模式启动的原因。

问题

即使没有设置文件,如何使应用程序以轻模式启动?

到目前为止尝试过

我尝试使用alias而不是int,但standaloneWindow没有要绑定的属性Material.theme

    Settings {
        // ...
        property alias materialTheme: standaloneWindow.???
    }

Any suggestion?

标签: qtqml

解决方案


正如@Mitch 所评论的,问题得到了解决:

    Settings {

        id: appSettings

        category: "Theme"

        // Set dark theme to be default for the very first launch (when settings file is NOT available)
        property int materialTheme: Material.Dark
    }

推荐阅读