c++ - 如何更新样式表的单个属性?

标签 c++ css qt

我有一个窗口:

class MyWindow : public QWindow
{
.....
};

MyWindow *window;

和一组样式表属性:

MyWindow
{
    style1: value1;
    style2: value2;
}

为了在窗口上设置这些属性,我必须调用:

window->setStyleSheet( "style1: value1" );
window->setStyleSheet( "style2: value2" );

例如设置QPushButton 的对齐需要设置text-align 属性。

现在假设我想修改 style1 的 value1 值。我可以通过两种方式做到这一点:

  1. window->setStyleSheet( "style1: new-value");

  1. window->setStyleSheet( "style1: new-value; style2: value2");

不同之处在于,对于第二种情况,我需要重建之前设置的整个样式表并附加我的更改。

现在的问题是 - 据您所知,是否有任何窗口/样式集我绝对必须按照方法 #2 进行?

当然,仅仅为了更改 1 个属性值而必须重建属性表会很奇怪,但我想问一下以防万一。

最佳答案

背景

In order to set those properties on the window I have to call:

window->setStyleSheet( "style1: value1" );
window->setStyleSheet( "style2: value2" );

样式表是 cascading , 但不是累积的,这意味着后面的样式表将取消前面的样式表。

考虑这个例子:

auto *label = new QLabel("test", this);

label->setStyleSheet("background-color: yellow");
label->setStyleSheet("color: red");

结果是:文本为红色,但背景为默认颜色。

如果最后两行交换位置,结果是:背景为黄色,但文本现在具有默认颜色。

所以,关于当你绝对必须按照#2 的方式的问题的答案是:

总是

解决方案

考虑到这一背景,为了回答标题中的问题,我建议您采用以下解决方案:

  1. 将样式表转换为 JSON
  2. 更新选择值
  3. 将 JSON 转换回样式表
  4. 为小部件设置新样式表

例子

建议的解决方案可能听起来很复杂,但幸运的是我准备了一个类 StylesheetManipulator,它具有必要的功能,以及如何使用它的示例:

StylesheetManipulator.h

#ifndef STYLESHEETMANIPULATOR_H
#define STYLESHEETMANIPULATOR_H

#include <qglobal.h>
#include <QJsonArray>

class StylesheetManipulator
{
public:
    static QString updateStylesheetProperty(const QString &styleSheet, const QString &selector, const QString &property, const QString &newValue);

private:
    static QJsonArray styleSheetToJson(const QString &styleSheet);
    static QJsonArray styleSheetPropertiesToJson(const QString &properties);
    static QJsonArray updateValue(const QString &selector, const QString &propertyName, const QString &newValue, const QJsonArray &jsonStyleSheet);
    static QString jsonToStyleSheet(const QJsonArray &jsonStyleSheet);
};

#endif // STYLESHEETMANIPULATOR_H

StylesheetManipulator.cpp

QString StylesheetManipulator::updateStylesheetProperty(const QString &styleSheet, const QString &selector, const QString &property, const QString &newValue)
{
    return jsonToStyleSheet(updateValue(selector, property, newValue, styleSheetToJson(styleSheet)));
}

QJsonArray StylesheetManipulator::styleSheetToJson(const QString &styleSheet)
{
    QJsonArray jsonStyleSheet;

    if (styleSheet.isEmpty())
        return jsonStyleSheet;

    foreach (const QString &style, styleSheet.trimmed().split("}")) {
        const QString &trimmedStyle(style.trimmed());

        if (!trimmedStyle.isEmpty()) {
            const QStringList &list(trimmedStyle.split("{"));

            jsonStyleSheet.append(QJsonObject {
                                 {"selector", list.first().trimmed()},
                                 {"properties", styleSheetPropertiesToJson(list.last())}
                             });
        }
    }

    return jsonStyleSheet;
}

QJsonArray StylesheetManipulator::styleSheetPropertiesToJson(const QString &properties)
{
    QJsonArray jsonProperties;

    if (properties.isEmpty())
        return jsonProperties;

    foreach (const QString &property, properties.trimmed().split(";")) {
        const QString &trimmedProperty(property.trimmed());

        if (!trimmedProperty.isEmpty()) {
            const QStringList &list(trimmedProperty.split(":"));

            jsonProperties.append(QJsonObject{
                                      {"name", list.first().trimmed()},
                                      {"value", list.last().trimmed()}
                                  });
        }
    }

    return jsonProperties;
}

QJsonArray StylesheetManipulator::updateValue(const QString &selector, const QString &propertyName, const QString &newValue, const QJsonArray &jsonStyleSheet)
{
    QJsonArray a;

    foreach (const QJsonValue &value, jsonStyleSheet) {
        const QJsonObject &currentStyle(value.toObject());
        const QString &currentSelector(currentStyle["selector"].toString());
        bool selectorFound = currentSelector == selector;
        QJsonArray properties;

        foreach (const QJsonValue &value, currentStyle["properties"].toArray()) {
            QJsonObject property(value.toObject());

            if (selectorFound && (property["name"].toString() == propertyName))
                property["value"] = newValue;

            properties.append(property);
        }

        a.append(QJsonObject{
                     {"selector", currentSelector},
                     {"properties", properties}
                 });
    }

    return a;
}

QString StylesheetManipulator::jsonToStyleSheet(const QJsonArray &jsonStyleSheet)
{
    QString styleSheet;

    foreach (const QJsonValue &value, jsonStyleSheet) {
        const QJsonObject &currentStyle(value.toObject());

        styleSheet.append(currentStyle["selector"].toString() + " {");

        foreach (const QJsonValue &value, currentStyle["properties"].toArray()) {
            QJsonObject property(value.toObject());

            styleSheet.append(" " + property["name"].toString() + ": " + property["value"].toString() + ";");
        }

        styleSheet.append(" } ");
    }

    return styleSheet;
}

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent)
{
    auto *label = new QLabel("test", this);
    auto *l = new QVBoxLayout(this);

    label->setStyleSheet("QFrame { background-color: yellow; border: 2px solid blue } QLabel { color: red; }");
    label->setStyleSheet(StylesheetManipulator::updateStylesheetProperty(label->styleSheet(), "QLabel", "color", "green"));

    l->addWidget(label);

    resize(300, 200);
}

示例的完整代码可在 GitHub 上获得。

该示例产生以下结果:

Window with a green text on yellow background surrounded by a blue border

请注意,虽然最初文本颜色设置为红色 (QLabel { color: red; }),但实际上已更改为绿色。

关于c++ - 如何更新样式表的单个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879480/

相关文章:

c++ - C++中括号的不同含义?

c++ - 如何将 C++ 库与 CGO 和 Swig 链接起来?

html - 用于创建复杂数学表达式的 CSS 框架

html - 自动调整图像大小的标题,有什么想法吗?

python - Pyside:在 QVBoxLayout 小部件中设置行的背景

c++ - CUDA 将 GpuMat 的 c 数组传递给内核

c++ - 是否可以在 Mac OS X 上使用 mmap() 避免磁盘使用?

html - 表格 td 中的边框半径和边框

c++ - QtConcurrent::map 显示没有任何好处

c++ - QWidget - 从 C++ 代码设置边框