PDA

View Full Version : Dynamically change spacing between icon and label in QPushButton



bernardoreis
30th August 2013, 22:49
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.


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.


class ProperlyAlignedPushButtonStyle : public QProxyStyle
{
public:
ProperlyAlignedPushButtonStyle() : QProxyStyle(QStyleFactory::create("windows")) {}

void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *widget) const
{
if (element == CE_PushButtonLabel) {
...
int iconSpacing = (textRect.width() - (labelWidth + textWidth) ) / 3;
...
else {
QProxyStyle::drawControl(element, opt, p, widget);
}
}
};



void OrientationButton::paintEvent(QPaintEvent* event) {
ProperlyAlignedPushButtonStyle pa;
pa.drawControl(QStyle::CE_PushButton, &getStyleOption(), &p, this);
}

Any ideas? Thanks in advance!

wysota
3rd September 2013, 19:54
In general trying to mix stylesheets with real styles is a bad idea. Decide to use one and stick with this decision.

bernardoreis
5th September 2013, 15:29
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.