I'm currently struggling with what should be an easy issue to solve. Many widgets support some sort of QSizePolicy. This includes the QPushbutton. In my case I have multiple buttons in a grid layout all of which have their QSizePolicy for both vertical and horizontal resizing set to expanding. This leads to the nead result of the buttons being resized according to the size of the widget which the grid layout is part of.
The problem comes from the way icons seem to be handled in Qt. QIcon does not have a QSizePolicy property (or at least I was unable to find one in the official documentation of Qt4 about QIcon and QAbstractButton). The only way seems to be using setIconSize() where you can give the maximum size of the icon. In addition one has to manually implement a routine on how the size is to be updated. In this case it would be (abstract writing here) icon.size == button.size-CONSTANT, where CONSTANT is some kind of a predefined factor (>= 0). Predefining various sizes (a list of QIcons) for the selected icon is also possible but still not a good option (read below why).
This seems to be a little bit of an overkill especially since QPushbutton supports QSizePolicy and the developer doesn't have to tinker in this departement at all unless he/she wants some special resizing going on. Also this sort of contradicts the support for SVG files that can be used in QIcon since, as we know, SVG = vector graphics = you can stretch those as much as you like without loss of quality.
Does anyone know an easy way to do that without the need to add additional even handles for resizing, providing a list of scales of the chosen icon or restricting the size to a maximum size?
PS: I have also looked into QPixmap - still the same issues there.
EDIT:
I forgot to mention one way I found out how to do what I wanted (the results are however not as pretty as I want them to be) - using the image property in the stylesheet for QPushbutton
. This however does not create an icon! If one doesn't really require a real icon and can just use a painted button using this property allows a huge flexibility in terms of resizing especially when using SVG.
Sub-classing
QPushButton
, as suggested by @Pavel in a comment, seems like a reasonable option to solve your issue. Below I provide a simple example that shows how this can be done inPySide
.Which results in:
The maximum size of the icon is limited by the size of the
png
used as input inQIcon
. If asvg
is used as input for theQIcon
, the scaling of the icon won't be limited in size. However, svg icons seems not to be supported in Windows7, but they are in Ubuntu.The code above would need to be expanded if a label is added to the button. Moreover, it would be possible to also scale the font size of the label to the button size if desired.
To persons who work in C++. Thanks a lot !
pushbuttoniconautoresize.h
pushbuttoniconautoresize.cpp