Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize QPushButton according to the size of it's icon?

Tags:

qt

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.
like image 459
kaa Avatar asked Aug 25 '14 07:08

kaa


2 Answers

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();
like image 152
Kosovan Avatar answered Oct 04 '22 07:10

Kosovan


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(),
                                       initSize,
                                       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.

like image 39
UmNyobe Avatar answered Oct 04 '22 07:10

UmNyobe