I thinks it's because min-width and min-height are not specified.
According to the documentation:
If this property is not specified, the minimum width is derived based
on the widget's contents and the style.
One possibility could be to get the size of the button before setting the style, and set that size when you apply the background color.
I.e. (in this example, we have a UI file with a pushbutton called pushButton
):
QString width ("min-width: " +
QString::number(ui.pushButton->size().width()) +
" px; " +
"max-width: " +
QString::number(ui.pushButton->size().width()) +
" px;");
QString height ("min-height: " +
QString::number(ui.pushButton->size().height()) +
" px; " +
"max-height: " +
QString::number(ui.pushButton->size().height()) +
" px;");
QString style ("#pushButton { " + width + height +
"background-color: black; }");
qApp->setStyleSheet(style);
I'm setting both min and max width and height because the reference says
If you want a widget with a fixed width, set the min-width and
max-width to the same value.
Of course, an easier solution could be to resize the pushbutton after setting the background color. Something like this:
int width = ui.pushButton->size().width();
int height = ui.pushButton->size().height();
QString style ("#pushButton { background-color: black; }");
qApp->setStyleSheet(style);
ui.pushButton->resize(width, height);