qtqpixmapqicon

How to set different icons to different buttons in Qt?


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?


Solution

  • 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());
    }