在运行时动态更改QML主题

Dynamically change QML theme at runtime

本文关键字:QML 主题 运行时 动态      更新时间:2023-10-06

我实际上使用的是这里提供的解决方案:https://stackoverflow.com/a/25864815/2425044

我想去掉import "MyTheme.js" as Theme;语句,以便在运行时动态加载特定主题(通常由用户选择)。

我目前正在做的是将我的每个Themes.js文件加载到一个qrc文件中:

  • redTheme.qrc包含Theme.js
  • blueTheme.qrc包含Theme.js

这些qrc文件被编译到外部二进制资源(rcc)中,并使用从二进制目录加载

registerResource(const QString &rccFileName, const QString &mapRoot = QString())

到目前为止,一切正常。唯一的问题是,我的QML文件中有一个import语句:

import "qrc:/redTheme/Theme.js" as Theme

因此,尽管将blueTheme.rcc注册为资源,但它永远不会被使用。

多亏了其他线程,我才能让它正常工作。

首先,像这个用户一样创建您的主题,它继承了AbstractStyle,允许更大的灵活性。

https://stackoverflow.com/a/25866188/2425044

然后,我们的property将由JS函数返回的值定义:

import "qrc:/graphics/componentCreation.js" as Theme
Item
{
    id: homeViewItem
    anchors.centerIn: parent
    // Load default theme at startup
    property AbstractTheme currentTheme: Theme.createThemeObject(homeViewItem, "qrc:/redTheme/redTheme.qml");
    Rectangle 
    {
        color: currentTheme.textColorStandard;
    }
}

componentCreation.js

// Create themes components and load them in the apps' QML files
var component;
var sprite;
function createThemeObject(item, themePath)
{
    component = Qt.createComponent(themePath);
    sprite = component.createObject(item);
    if (sprite === null)
        console.log("componentCreation.js: error creating " + themePath + " object");
    else
        return sprite;
}

假设用户点击Button:时您想更改主题

Button
{
    id: themeButton
    text: "Change to blue theme"
    onClicked:
    {
        // Remove content of redTheme.rcc, register blueTheme.rcc
        cpp_class.changeTheme("redTheme", "blueTheme")
        // blueTheme's content is now available, let's fill its content into a QML object
        currentTheme = Theme.createThemeObject(homeViewItem, "qrc:/blueTheme/blueTheme.qml")
    }
}

请记住,redTheme.qmlblueTheme.qml

以下是changeTheme(const QString&, const QString&)的定义,它注销旧主题并注册新主题:

void cpp_class::changeTheme(const QString &oldTheme, const QString &newTheme)
{
    bool un = QResource::unregisterResource(QCoreApplication::applicationDirPath() + "/data/themes/" + app + "/" + oldTheme + ".rcc");
    if (!un)
        std::cerr << oldTheme.toStdString() << "could not be unregistered" << std::endl;
    bool in = QResource::registerResource(QCoreApplication::applicationDirPath() + "/data/themes/" + app + "/" + newTheme + ".rcc");
    if (!in)
        std::cerr << newTheme.toStdString() << "could not be registered as an external binary resource" << std::endl;
}

其他帮助过我的线程:

https://wiki.qt.io/Qml_Styling

http://www.slideshare.net/BurkhardStubert/practical-qml-key-navigation(从幻灯片34开始)