Ruslan
Ruslan

Reputation: 19120

How to set an icon to a new button in QDialogButtonBox?

I'm trying to make a custom button with an icon in QDialogButtonBox in a Qt5 program (Qt 5.5.1) on Kubuntu 14.04. Reading this answer, I understand that it's not recommended to simply edit the stock buttons, so I use QDialogButtonBox::addButton with my custom button. But for some reason, although I do succeed in changing icon of the stock button, my custom button still remains without any icon after using QPushButton::setIcon.

Here's the code

#include <QApplication>
#include <QDialogButtonBox>
#include <QPushButton>

int main(int argc, char** argv)
{
    QApplication app(argc,argv);

    QDialogButtonBox bbox(QDialogButtonBox::Close);

    const auto button=new QPushButton(QObject::tr("Convert..."));
    bbox.addButton(QObject::tr("Convert..."), QDialogButtonBox::ApplyRole);
    const auto icon=QIcon::fromTheme("system-run");
    // This doesn't work - the button remains without icon
    button->setIcon(icon);
    // But this does
    bbox.button(QDialogButtonBox::Close)->setIcon(icon);

    bbox.show();

    return app.exec();
}

What am I doing wrong? How can I have an icon on my custom button without the need to edit stock buttons?

Upvotes: 1

Views: 1447

Answers (1)

thuga
thuga

Reputation: 12931

You are creating two buttons. One button which you don't show anywhere, and one that you add in bbox. And you are setting the icon for the button that you don't show anywhere.

Fix your code so you don't create two separate buttons, and set an icon for the button you are putting in bbox:

QPushButton *button = bbox.addButton(QObject::tr("Convert..."), QDialogButtonBox::ApplyRole);
...
button->setIcon(icon);

Upvotes: 4

Related Questions