简体   繁体   English

如何根据它的图标大小调整QPushButton的大小?

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

I need the flat QPushButton with icon. 我需要带有图标的扁平QPushButton。 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. 由于图标通常是方形的,您会注意到我提供的比较函数仅使用QSize对象中的宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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