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.
Qt Code:
  1. if (!button->icon.isNull()) {
  2. ...
  3. QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
  4. int labelWidth = pixmap.width();
  5. int labelHeight = pixmap.height();
  6. int iconSpacing = 4; //### 4 is currently hardcoded in QPushButton::sizeHint()
  7. int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
  8. if (!button->text.isEmpty())
  9. labelWidth += (textWidth + iconSpacing);
  10. ...
  11. }
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.
Qt Code:
  1. class ProperlyAlignedPushButtonStyle : public QProxyStyle
  2. {
  3. public:
  4. ProperlyAlignedPushButtonStyle() : QProxyStyle(QStyleFactory::create("windows")) {}
  5.  
  6. void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p, const QWidget *widget) const
  7. {
  8. if (element == CE_PushButtonLabel) {
  9. ...
  10. int iconSpacing = (textRect.width() - (labelWidth + textWidth) ) / 3;
  11. ...
  12. else {
  13. QProxyStyle::drawControl(element, opt, p, widget);
  14. }
  15. }
  16. };
To copy to clipboard, switch view to plain text mode 
Qt Code:
  1. void OrientationButton::paintEvent(QPaintEvent* event) {
  2. ProperlyAlignedPushButtonStyle pa;
  3. pa.drawControl(QStyle::CE_PushButton, &getStyleOption(), &p, this);
  4. }
To copy to clipboard, switch view to plain text mode 
Any ideas? Thanks in advance!