Qt 在样式表中使用调色板颜色

Nel*_*Dav 1 qt qtstylesheets qpalette

在 qt 中,您通常QWidget使用QPalette.

例子:

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

QLineEdit *line = new QLineEdit();
line->setPalette(palette);
Run Code Online (Sandbox Code Playgroud)

现在我有一个小问题。无法使用QPalette. 这意味着,我必须使用QStyleSheet.

例子:

QLineEdit *line = new QLineEdit();
line.setStyleSheet("border: 1px solid green");
Run Code Online (Sandbox Code Playgroud)

但是现在我不能用 设置 QLineEdit 的基色QPalette,因为QLineEdit的背景颜色不再连接到QPalette::base. 这意味着,下面的代码不会改变background-colorQLineEdit

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

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

但是background-color,在样式表中定义QLineEdit 的是不可能的,因为background-colorQLineEdit必须是动态的。

我的问题:如何连接QLineEditwith的背景颜色QPalette::base以动态定义background-colorof ?QLineEditQPalette

Max*_*rno 10

或者:

line->setStyleSheet(QStringLiteral(
    "border: 1px solid green;"
    "background-color: palette(base);"
));
Run Code Online (Sandbox Code Playgroud)

参考:http : //doc.qt.io/qt-5/stylesheet-reference.html#paletteole

使用PaletteRole还可以让 CSS 位于单独的文件/源中。


G.M*_*.M. 5

只需在运行时构建所需的QString...

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

上述结果应该会导致QString诸如...

border: 1px solid green;
background-color: #ffffffff;
Run Code Online (Sandbox Code Playgroud)

然后...

line->setStyleSheet(style_sheet);
Run Code Online (Sandbox Code Playgroud)