Qt5样式表:仅在默认设置下应用样式

时间:2018-05-12 04:33:11

标签: qt qt5 qtstylesheets

我在Qt5中玩样式表。这是一个例子:

QWidget {
    color: #b1b1b1;
    background-color: #323232;
    font-size: 12px;
}

QSpinBox, QDoubleSpinBox {
    color: black;
    background-color: darkorange;
}

QLabel {
    background-color: transparent;
}

然后我在主要设置样式表:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setStyle("Fusion");

    Widget w;
    QFile file("://mystylesheet");
    file.open(QFile::ReadOnly);
    QString stylesheet = file.readAll();
    file.close();
    w.setStyleSheet(stylesheet);
    w.show();

    return a.exec();
}

但是它会覆盖我在表单编辑器中设置的任何自定义值。相反,我想完全相反:样式表应该设置控件的默认属性,然后我可以覆盖它们在编辑器中设置不同的值。

是否可能以及如何?

例如:我可能想要一些具有不同背景颜色的标签:如果我在编辑器中设置了一个标签,它就不应该被样式表覆盖。

1 个答案:

答案 0 :(得分:0)

如果您希望表单上写的属性不被.qss覆盖,那么您应该使用#选择器,例如,如果您的QLabel具有customlabel objectName,那么您可以使用以下内容在表单上进行设置:

QLabel#customlabel { 
    background-color: gray 
}

示例:

#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>

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

    const std::string qss = R"(QWidget {
                            color: #b1b1b1;
                            background-color: #323232;
                            font-size: 12px;
                            }

                            QSpinBox, QDoubleSpinBox {
                            color: black;
                            background-color: darkorange;
                            }

                            QLabel {
                            background-color: transparent;
                            })";

    QWidget w;
    QVBoxLayout lay(&w);
    for(const QString & name: {"label1", "label2", "label3"}){
        QLabel *label = new QLabel(name);
        label->setObjectName(name);
        lay.addWidget(label);
    }
    QLabel *label = new QLabel("customlabel");
    label->setObjectName("customlabel");
    lay.addWidget(label);
    // emulate the Qt Designer form
    label->setStyleSheet("QLabel#customlabel{ background-color: gray }");

    // use .qss
    w.setStyleSheet(QString::fromStdString(qss));
    w.show();

    return a.exec();
}

输出:

enter image description here

相关问题