5
votes

I need the flat QPushButton with icon. The problem is the size of the button is much bigger than the size of icon. Is there a way to set the size of button according to the size of icon, without using magic numbers:

QIcon icon = GetIcon();
QPushButton* btn = new QPushButton( icon, "" ); 
btn->setFlat( true );
btn->setCheckable( true );

btn->setFixedSize( 16, 16 ); // These values should be calculated from the icon size.
2

2 Answers

5
votes

Try this.

QIcon ic("://icons/exit_6834.ico");
ui->pushButton_5->setFixedSize(ic.actualSize(ic.availableSizes().first()));//never larger than ic.availableSizes().first()
ui->pushButton_5->setText("");
ui->pushButton_5->setIcon(ic);
ui->pushButton_5->setIconSize(ic.availableSizes().first());
qDebug() << ic.availableSizes();
2
votes

Usually it is the other way around, an icon is supposed to provide different resolutions. But to do what you want you need to find the closest size supported by the icon, given an initial size as reference.

static bool less(const QSize& a, const QSize&b)
{
   return a.width() < b.width(); 
}

QSize closestIconSize(const QIcon& icon, QSize initSize)
{
    QList<QSize> qlistSizes = icon.availableSizes();
    QList<QSize>::const_iterator it = std::lower_bound(
                                       qlistSizes.begin(), 
                                       qlistSizes.end(),
                                       less);
    return it != qlistSizes.end() ? *it : initSize;
}

As icons are usually square you will notice that the comparison function I provide is only using the width in the QSizeobject.