2

I have a lot of buttons that I want to set an icon to. Moreover, this icon is not the same for each button.

I do this just for one of them:

QString str=(qApp->applicationDirPath());
str.append("/pic/kb.png");
QPixmap pixmap(str);
QIcon ButtonIcon(pixmap);
ui->btnShowKB->setIcon(ButtonIcon);
ui->btnShowKB->setIconSize(pixmap.rect().size());

but I really have a lot of button (btn1,btn2,btn3,....,btn9).

How can I set other images for other buttons (/pic/1.png , /pic/2.png , /pic/3.png , .... , /pic/9.png)? Do I have to create a new QPixmap for each one, or is there a simpler solution?

Vincenzo Maggio
  • 3,787
  • 26
  • 42
MHM
  • 261
  • 1
  • 2
  • 15

2 Answers2

3

First of all, if you're using designer, so use it fully, not only for adding widgets. You can add icon to your buttons from there. Just add resource file to your project, load images to it and then choose needed to buttons. Or, if you don't want use resource file, you can upload images from any directory.

Shtol Krakov
  • 1,260
  • 9
  • 20
  • thanks. can you give me example that I understand it. I am new .sorry – MHM May 12 '16 at 06:39
  • 1
    Go to designer in Qt Creator, select needed button. Then, by default on the right side, find object's properties area. There find `QPushButton` area and find **icon** property. There you can add or choose (if you using resource file) your icon. – Shtol Krakov May 12 '16 at 07:32
2

The way you are doing it, the only things that change in your code is obviously the name of the file and the button you want to set an icon to. So you should create a method taking a QString and a button as parameters, and call it whenever you need it for your desired button. (In the below code, I use a QPushButton as a button, maybe it is different for you so change it accordingly).

void yourClass::setButtonIcon(QString iconPath, QPushButton* button)
{
    qApp->applicationDirPath().append(iconPath);
    QPixmap pixmap(str);
    QIcon buttonIcon(pixmap);
    button->setIcon(ButtonIcon);
    button->setIconSize(pixmap.rect().size());
}
IAmInPLS
  • 4,051
  • 4
  • 24
  • 57