Shaiful Islam
Shaiful Islam

Reputation: 442

How to change QMessagebox button and background color?

I want to change background color and ok button color. But If I change background color button color is automatically changed.

My code:

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

Upvotes: 0

Views: 733

Answers (1)

user17726418
user17726418

Reputation: 2363

Explanation:

The Ok button (a QPushButton) is a child of QMessageBox, so when you set its stylesheet, and then set QMessageBox's stylesheet, the button's stylesheet gets overridden. Probably because, when in conflict, the parent's stylesheet gets set. So you need to avoid that conflict, to achieve the look you need.

Solution 1:

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

This is the result:

Result

You need to specify the green background color for QMessageBox, if you don't (the way you're doing it), it will override every other style sheet you apply to any of its children, even if applied after.

To demonstrate, this will also not work:

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

It will result in a green background for the button as well.

Solution 2

You could set your msgBox stylesheet the way you're doing, and for the button, you could change its stylesheet directly as follows:

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

This is the equivalent of specifying object names in stylesheet, but you don't need to bother with that here, because the style conflict is between 2 different objects, a QMessageBox, and a QPushButton.

Upvotes: 0

Related Questions