In my Qt 5.7.1 application I've some buttons, I want to align button's icons to left and centre text, but there is no option in designer to do this.
I can align icon and text left by adding to button stylesheet this code:
text-align:left;
But it's not what I want to achieve. So, could you please tell me, If there is any option to align icon to left, and keep text aligned center? Thank you for help.
Less code way without breaking UI style
Remember to send setText signals to textLabel instead of pushButton
To get this level of control you will need to write some code to override the style for your platform. This is best done using a QProxyStyle. In this case we are looking for when the style is asked to draw a CE_PushButtonLabel (the label includes the icon, and they are hard coded in Qt to be aligned together).
You need to implement a QProxyStyle and override the drawControl() method. The code for the bulk of it is copied directly from the Qt source code for the default drawcontrol method (in qcommonstyle.cpp) - so although it looks lengthy, it is mostly doing what Qt already does. I put extra /****/ markers around the sections I modified. This won't show up in Qt Designer, but will work at runtime.
Final result (shown on mac, should match platform you're on)
main.cpp:
mystyle.h
mystyle.cpp
Simply specialize
QPushButton
and overridepaintEvent
andsizeHint
, as proposed by cbuchart here. Then use it as a regularQPushButton
.MyButton
declaration and implementation:mybutton.h:
mybutton.cpp:
Exemple of usage:
Here is an example where "Promote widget" feature in Qt Designer was used to create
MyButton
from .ui files:mainframe.ui:
mainwindow.h:
mainwindow.cpp:
main.cpp:
Results in:
QPushButton
(usingQPushButton::setText
), you don't need to keep a reference to a mockupQLabel
to change button's text.