简体   繁体   中英

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

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.

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

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 QSize object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM