How to smoothly scale background images in Qt styles?

By default, Qt uses a very simple, fast, and ugly way to scale images, Qt::FastTransformation , possibly interpolating the nearest neighbor or something very similar.

When working with QPixmap you can select visually better scaling, for example,

 pixmap = pixmap.scaledToHeight(height, Qt::SmoothTransformation); 

However, what can we do if the image is not in the QPixmap object, but just the background of the button or some other widget?

For example, this is a very simple way to create an automatic size adjustment, a fully customizable button, well suited for a resolution-independent application when used with layouts and setStretch() .

 ui->pushButton->setStyleSheet( "QPushButton { border-image: url(:/img/button.png) 0 0 0 0 stretch stretch; }" "QPushButton:checked { border-image: url(:/img/button_checked.png) 0 0 0 0 stretch stretch; }" "QPushButton:pressed { border-image: url(:/img/button_pressed.png) 0 0 0 0 stretch stretch; }" "QPushButton:checked:pressed { border-image: url(:/img/button_checked_pressed.png) 0 0 0 0 stretch stretch; }" ); 

I used border-image instead of background-image due to a lack of Qt style sheets.

How can I get smoother scaling with images used in style sheets?

Implementing the same thing with pixmaps is much less elegant. I should always intercept resize events, recount the new sizes of all my widgets and redraw them manually.

Edit:

Interestingly, smooth scaling works with styles if the image is enlarged, but not when it is compressed.

In the following example, the 32 * 32 icon is used in the first line, and a single grid larger than 2000 * 2000 is used in the second line.

example

+8
css qt
source share
1 answer

Internally, Qt uses QPainter to draw styles, and QPainter uses bilinear interpolation when drawing scaled pixmaps. This has a significant quality disadvantage when the scaling factor is small enough, see this bug report . For best quality, the original source image should always be within the [0.5, 2.0] coefficient of the target size. AFAICT there is no easy way out of this limitation.

+1
source share

All Articles