qtqtstylesheetsqpalette

Qt use palette color in stylesheet


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?


Solution

  • 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);