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);
...
}
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);
...
}
To copy to clipboard, switch view to plain text mode
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")) {}
{
if (element == CE_PushButtonLabel) {
...
int iconSpacing = (textRect.width() - (labelWidth + textWidth) ) / 3;
...
else {
QProxyStyle::drawControl(element, opt, p, widget);
}
}
};
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);
}
}
};
To copy to clipboard, switch view to plain text mode
void OrientationButton
::paintEvent(QPaintEvent* event
) { ProperlyAlignedPushButtonStyle pa;
pa.
drawControl(QStyle::CE_PushButton,
&getStyleOption
(),
&p,
this);
}
void OrientationButton::paintEvent(QPaintEvent* event) {
ProperlyAlignedPushButtonStyle pa;
pa.drawControl(QStyle::CE_PushButton, &getStyleOption(), &p, this);
}
To copy to clipboard, switch view to plain text mode
Any ideas? Thanks in advance!
Bookmarks