Introduction
I recently needed to display a series of buttons for my shelf tool, the problem I’m having with this is that
although every button has an icon and text label, they are displayed as different width. Using center-align
made it look not uniform.
Should I go with left-align
? Well, there are buttons with relatively longer label and some with shorter ones,
so it doesn’t look nice either with empty spaces on the right side.
So the solution is obvious, separate the alignment of the icon and the label: the icon stays left-align
to
give a clear sign of broader, and the label would be center-align
to make the width look uniform.
(Left: default center align, Center: left align, Right: custom align)
In the following section, I will demonstrate three methods of achieving this custom alignment effect:
Overriding QPushButton paintEvent()
This method subclass from QPushButton
and override the paintEvent()
and sizeHint()
to extend how a button is drawn;
The alignment of content of the button is default to center-aligned
, but
we make the pixmap to be drawn on the left-side (5px margin against the left border)
With this method, we no longer use QIcon
, we use QPixmap
instead; that is why
we created a custom setPixmap()
method to our MyButton
to give user access
to the pixmap being drawn.
Custom layout inside pushbutton
Here is another interesting approach:
this method defaults its style to left-aligned
, but it only contains the icon.
What about the push button label(text)?
It is actually a QLabel
placed in the QPushButton
layout, and being vertically
center-aligned
; To modify the push button text, use setText()
to the label
inside the button layout, instead of the button.
Use QProxyStyle
I haven’t personally test it because my Qt python binding doesn’t have QProxyStyle included
but it’s worth putting it here in case someone is able to try it.
1 | class ProxyStyle(QtWidgets.QProxyStyle): |
Reference
Stack Overflow - QPushButton icon aligned left with text centered
Stack Overflow - qpushbutton icon left alignment text center alignment