Reputation: 1827
I want to modify the background-color of QPushButtons. The problem is that modifying the background color using setStyleSheet("QPushButton { background-color: #00FF00 }");
, the button size also scales.
before
after
I understand that by changing the background-color, the entire button style sheet gets overwritten and reset to some default (How to override just one property:value pair in Qt StyleSheet).
My question is: how can I set the size of the button such that it is the same size as the original?
I am using MacOSX and I tried all combinations of height, minimum-height, padding.
Upvotes: 4
Views: 1008
Reputation: 137
If it's just about setting the background color, then using the QPalette would be an option.
QPushButton button;
QPalette palette = button.palette();
palette.setColor(QPalette::Background, QColor("#00FF00");
button.setPalette(palette);
Upvotes: 2
Reputation: 7170
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);
Upvotes: 1