when I add an icon to my button, it appears left to my text and if I shrink the button size, part of the icon actually remains outside of the button. I want the icon to be the button, as in - to be the entire texture of the button. How can i center it, or is the icon not what I'm looking for?
Asked
Active
Viewed 1,302 times
0
-
possible duplicate of [Setting background image for QPushButton](http://stackoverflow.com/questions/2671842/setting-background-image-for-qpushbutton) – Miki Jul 09 '15 at 12:56
-
If you just want an icon, remove the text by setting it to "". – TheDarkKnight Jul 09 '15 at 16:05
2 Answers
3
You have to use stylesheets for this.
For the image to take all the available space :
QPushButton
{
border-image: url(":/your_image");
}
For the image to be in the center with a constant size :
QPushButton
{
background-image: url(":/your_image") ;
background-repeat: no-repeat;
background-position: center;
}

dydil
- 949
- 7
- 20
-
I suppose @ulak-blade wants to change only a certain button, so it's preferable to use something like `QPushButton#your_button` – Tarod Jul 09 '15 at 13:09
-
You're right but it depends on which widget he applies the stylesheet to. I was thinking about the simplest way : changing the stylesheet of this particular button from QtDesigner. – dydil Jul 09 '15 at 13:18
-
2
A solution would be to use CSS instead the setIcon
method. But anyway, you should get the right behaviour with the next code:
QPushbutton *button = new QPushbutton;
QPixmap pixmap("path_to_image");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
As I said before, you can get a very good solution applying styles:
button->setStyleSheet("border-image:url(:/path/to/image);");
I have a repo in GitHub where you can play with different stylesheets. In fact, there are three qss which are using the background-image
property.

Tarod
- 6,732
- 5
- 44
- 50