Qt image size in push buttons and labels
Often we want to show an image in a push button (QPushButton) or in a window (using QLabel). The automatic resizing offered by the Qt framework isn’t always working, so I use the following trick.
The following global functions are defined:
#include <QApplication>
double getLogicalDPI(void)
{
return QApplication::screens().at(0)->logicalDotsPerInch();
}
double get_resolution_ratio_vs_mdpi(void)
{
const double mdpi_DPI=80.; // really this is a "logical" DPI resolution - accounting for some scaling by Qt, the OS and so on. Use this.
static double resolution_ratio=
getLogicalDPI()/mdpi_DPI;
return resolution_ratio;
}
In any form constructor, we do the following:
{
...
ui->setupUi(this);
...
// Fix icon sizes for high-DPI displays
double scale_factor=get_resolution_ratio_vs_mdpi();
// for icons in push buttons:
ui->acceptButton->setIconSize(ui->acceptButton->iconSize()*scale_factor);
// for icons in labels:
ui->label_chat_icon->setFixedSize(ui->label_chat_icon->minimumSize()*scale_factor);
...
}
In any .ui file, we do the following. For a push button, we set the iconSize property to the size we would like at mdpi (normal resolution). For a QLabel, we set sizePolicy to Fixed, then minimumSize = maximumSize = the size we would like at mdpi (normal resolution).