如何在 Qt Design Studio 中编辑单例样式文件中组件的属性(颜色)?

问题描述 投票:0回答:1

我有一个用 QML 和 C++ 实现的桌面应用程序。应用程序和 UI 支持深色和浅色主题。几乎所有组件颜色都放置在单例样式文件中,该文件检查当前安装的主题。

// main.cpp

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    qQmlEngine = new QQmlApplicationEngine(&app);

    qQmlEngine->rootContext()->setContextProperty("ThemeMode", "dark");
        const QUrl url(QStringLiteral("qrc:/qml/main.qml"));
    qQmlEngine->load(url);

    return app.exec();
}
// Style.qml

pragma Singleton

import QtQuick 2.15

QtObject {
    property string mode: ThemeMode
    property color backgroundColor: mode === "light" ? 'white' : 'black'
    property color textColor: mode === "light" ? 'black' : 'white'
}
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    height: 320
    width: 240
    Rectangle {
        anchors.fill: parent
        color: Style.backgroundColor
        Text {
            text: "Hello world"
            color: Style.textColor
        }
        Text {
            text: "Hello world"
            color: Style.textColor
        }
    }

}

我希望设计师(可能不了解 QML 和 JavaScript)能够在 Qt Design Studio 中编辑用户界面,而无需编译整个应用程序。

例如,在 Qt Design Studio 中编辑组件颜色时,颜色直接在选定的当前组件中发生变化。显然,Qt Design Studio 对颜色位于

Style.qml
的事实一无所知。此外,我们还通过三元运算符检查当前安装了哪个主题。对此可以做什么?

mode === "light" ? 'white' : 'black'

我如何为 ThemeMode 变量创建假数据,该变量放置在 C++ 代码的上下文中?谢谢大家。

c++ qt mocking qml qt-design-studio
1个回答
0
投票

您可以利用

Singletons + Inheritance
轻松实现多种样式。请注意,这也适用于存储在 QML 中的设置文件,并且非常适合覆盖调试与发布或 Windows 与 Linux 等内容的值。

基础主题.qml

@pragma Singleton

QObject { // Set the values to what you will use most commonly
  property color fontColor: "black"
  property int fontSizePx: 32
  property int fontSizePt: 14
  property color backgroundColor: "black"
  property color accentColor1: "green"
}

主题WithBigFont.qml

@pragma Singleton
BaseTheme {
  // Just override the parts you want to change
  fontSizePx: 42
}

main.qml

import BaseTheme
import ThemeWithBigFont

QObject {
  id: myObject
  property BaseTheme activeTheme: ThemeWithBigFont // Change freely

//These update if you change activeTheme
  property color backgroundColor: activeTheme.backgroundColor 

  property int fontSize: activeTheme.fontSizePx 
}

您也可以通过使用组合和构建器来实现相同的目的,但这似乎没有必要的创造性。如果您能找到一个合法的用例,我会考虑扩展这个答案。

© www.soinside.com 2019 - 2024. All rights reserved.