如何更改QMessagebox按钮和背景颜色? [重复]

问题描述 投票:0回答:1

我想更改背景颜色和确定按钮颜色。但是如果我更改背景颜色按钮颜色会自动更改。

我的代码:

auto msgBox = new QMessageBox();
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->setMinimumSize(300, 300);
msgBox->setWindowTitle("Error");
msgBox->setIcon(QMessageBox::NoIcon);
msgBox->setStyleSheet("QPushButton{ color: red; background-color: white }");
msgBox->setStyleSheet("background-color:green;");
c++ qt qtstylesheets qmessagebox
1个回答
1
投票

说明:

Ok 按钮

QPushButton
)是
QMessageBox
的子级,因此当您设置其样式表,然后设置
QMessageBox
的样式表时,该按钮的样式表将被覆盖。可能是因为,当发生冲突时,父级的样式表会被设置。因此,您需要避免这种冲突,以获得您需要的外观。

解决方案1:

auto msgBox = new QMessageBox();
msgBox->setMinimumSize(300, 300);
msgBox->setStyleSheet("QMessageBox{ background-color: green;}"
                      "QPushButton{ background-color: white; color: red;}");

这是结果:

您需要为

QMessageBox
指定绿色背景颜色,如果您不这样做(按照您的方式),它将覆盖您应用于其任何子项的所有其他样式表,即使是在之后应用的。

为了演示,这也行不通:

msgBox->setStyleSheet("background-color:green;");
msgBox->styleSheet().append("QPushButton{ color: red; background-color: white }");

这也会导致按钮出现绿色背景。

解决方案2

您可以按照自己的方式设置

msgBox
样式表,对于按钮,您可以直接更改其样式表,如下所示:

msgBox->setStyleSheet( "background-color: green;" );
msgBox->button(QMessageBox::Ok)->setStyleSheet( "background-color: white; color: red;" );

这相当于在样式表中指定对象名称,但您无需在这里操心,因为样式冲突发生在 2 个不同的对象(a

QMessageBox
QPushButton
)之间。

© www.soinside.com 2019 - 2024. All rights reserved.