Qt – How to resize QPushButton according to the size of it’s icon

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.

Best Answer

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