2

I'm beginning in Qt, and I want to set a QPushButton to a different icon whenever somebody hovers the mouse over it. Here's my code so far:

#include <QPushButton>

QPushButton *button = new QPushButton(mainWindow);
button->setIcon(QIcon(":/icons/button.png"));
button->setIconSize(QSize(128,56);
button->setGeometry(0,0,128,56);

I've heard something about stylesheets, but I have no clue how to use them and all the documentation is very confusing for me. Could somebody explain how I can set the icon to ":/icons/button-hover.png" whenever the mouse hovers on the button? Also, unless it's like exactly the same for when it's pressed, it would be great if you could show me that too.

Thanks in advance :)

Connor M
  • 331
  • 3
  • 5
  • 18

2 Answers2

4

You can set the style sheet for the QPushButton instance as shown below:

button->setStyleSheet("QPushButton {border-image: url(c:/Data/navArrowsSelected.png); } QPushButton:focus { border-image: url(c:/icons/button-hover.png }");
Flovdis
  • 2,945
  • 26
  • 49
Hariprasad
  • 3,556
  • 2
  • 24
  • 40
  • This doesn't do exactly what I want. I'm not really even sure if it's the stylesheet I should be using to do this, but this does not appear to change the image when I hover the mouse over it, and also the image is kind of in the background of the button when I would prefer it be like it was when i used setIcon(). – Connor M Aug 22 '13 at 18:43
  • Use `border-image` instead of `background-image`. I have changed the answer accordingly. – Hariprasad Aug 22 '13 at 18:49
  • 2
    Ok, seems to work now. I changed :focus to :hover and added an extra ")" after .png and it works. Thanks! – Connor M Aug 22 '13 at 18:58
1

did you try the qproperty- syntax?

QToolButton {
    qproperty-icon: url(:/icon.png);
}
Daniel
  • 573
  • 4
  • 11
  • It works, but doesn't work on a state change for no apparent reason. See http://stackoverflow.com/questions/20573944/change-icon-on-state-change-using-qt-stylesheet – Phlucious May 15 '15 at 17:28