Dynamically change spacing between icon and label in QPushButton
I am frustratingly trying to dynamically change the spacing between the icon and the label inside a QPushButton, for different screen sizes. Looking through the source code in qcommonstyle.cpp, this spacing is hardcoded as 4.
Code:
if (!button->icon.isNull()) {
...
QPixmap pixmap
= button
->icon.
pixmap(button
->iconSize, mode, state
);
int labelWidth = pixmap.width();
int labelHeight = pixmap.height();
int iconSpacing = 4; //### 4 is currently hardcoded in QPushButton::sizeHint()
int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
if (!button->text.isEmpty())
labelWidth += (textWidth + iconSpacing);
...
}
Changing it to what I want seems trivial, if I could recompile QT. But there should be a solution using default/precompiled libraries. I tried to create a QProxyStyle, which would basically reimplement the CE_PushButtonLabel case of its drawControl method. But then it wasn't properly drawn, changing the previously css-setted border and the background-color of the pressed state. I applied the following QProxyStyle using both QApplication::setStyle() and directly instantiating the style in the paintEvent of my button, neither changed only the spacing.
Code:
class ProperlyAlignedPushButtonStyle : public QProxyStyle
{
public:
ProperlyAlignedPushButtonStyle
() : QProxyStyle
(QStyleFactory::create("windows")) {}
{
if (element == CE_PushButtonLabel) {
...
int iconSpacing = (textRect.width() - (labelWidth + textWidth) ) / 3;
...
else {
QProxyStyle::drawControl(element, opt, p, widget);
}
}
};
Code:
void OrientationButton
::paintEvent(QPaintEvent* event
) { ProperlyAlignedPushButtonStyle pa;
pa.
drawControl(QStyle::CE_PushButton,
&getStyleOption
(),
&p,
this);
}
Any ideas? Thanks in advance!
Re: Dynamically change spacing between icon and label in QPushButton
In general trying to mix stylesheets with real styles is a bad idea. Decide to use one and stick with this decision.
Re: Dynamically change spacing between icon and label in QPushButton
You're probably right. It doesn't look like that I can easily retrieve stylesheets' infomation and use it to paint a widget myself.
Thanks for the advice.