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;");
Explanation:
The Ok button (a
QPushButton) is a child ofQMessageBox, so when you set its stylesheet, and then setQMessageBox'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:
This is the 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:
It will result in a green background for the button as well.
Solution 2
You could set your
msgBoxstylesheet the way you're doing, and for the button, you could change its stylesheet directly as follows: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 aQPushButton.