0
votes

I'm playing with stylesheets in Qt5. Here an example:

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

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

QLabel {
    background-color: transparent;
}

then I set the stylesheet in the main:

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();
}

But it overwrites any custom value I set in the Form editor. Instead I want exactly the opposite: the stylesheet should set the default properties for the controls, then I can override them setting a different value in the editor.

Is it possible and how?

For example: I might want to have some labels with a different background color: if I set one in the editor it should not be overwritten by the stylesheet.

1

1 Answers

0
votes

If you want the properties written on the form not to be overwritten by your .qss then you should use the # selector, for example if your QLabel has the customlabel objectName then you can set it on the form using the following:

QLabel#customlabel { 
    background-color: gray 
}

Example:

#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();
}

Output:

enter image description here