Qt use palette color in stylesheet

7.3k views Asked by At

In qt you normally set the color of a QWidget with the QPalette.

Example:

QPalette palette = new QPalette();
palette.setBrush(QPalette::Base, this->palette().backgorund());

QLineEdit *line = new QLineEdit();
line->setPalette(palette);

Now I have a little problem. It is not possible to change the bordercolor of a QLineEdit with the QPalette. That means, that I have to use a QStyleSheet.

Example:

QLineEdit *line = new QLineEdit();
line.setStyleSheet("border: 1px solid green");

But now I can't set the basecolor of the QLineEdit with QPalette, because the background-color of QLineEdit is not longer connected to QPalette::base. That means, that the following code wouldn't change the background-color of the QLineEdit:

QPalette palette = new QPalette();
palette.setBrush(QPalette::Base, this->palette().backgorund());

QLineEdit *line = new QLineEdit();
line->setPalette(palette);
line->setStyleSheet("border: 1px solid green");

But it is not possible, to define the background-color of the QLineEdit in the StyleSheet, because the background-color of the QLineEdit have to be dynamically.

My question: How to connect the background-color of the QLineEdit with QPalette::base to define the background-color of QLineEdit dynamically with QPalette?

3

There are 3 answers

1
G.M. On BEST ANSWER

Just construct the required QString at runtime...

auto style_sheet = QString("border: 1px solid green;"
                           "background-color: #%1;")
  .arg(QPalette().color(QPalette::Base).rgba(), 0, 16);

The above should result in a QString such as...

border: 1px solid green;
background-color: #ffffffff;

Then...

line->setStyleSheet(style_sheet);
0
NelDav On

I found a solution for my situation. Because I only want to mask the border, and don't want to color it, I can use the method QLineEdit::setFrame(bool). But what is, if I want to color the frame like in my example above? I didn't find a solution for that so far. I am happy about every answer.

3
Maxim Paperno On

Alternatively:

line->setStyleSheet(QStringLiteral(
    "border: 1px solid green;"
    "background-color: palette(base);"
));

Reference: http://doc.qt.io/qt-5/stylesheet-reference.html#paletterole

Using PaletteRole also lets the CSS be in a separate file/source.