A Simple Guide to Resizing and Scaling Pixmap in Qt

Introduction

During my attempts to create custom alignment push buttons, I encountered an issue with icon having jagged looking (even if with low resolution).

I use a custom paintEvent() drawing QPixmap, and this happens when I use scaled() to resize my pixmap.

I noticed the icon does not have the jagged look with the built-in setIcon() and setIconSize in QPushButton. So I know there’s some wrong with my approach.

Example

To really show out the difference, I first reduce the resolution of my image.

1
2
3
4
5
low_rez = QtCore.QSize(40, 40)
high_rez = QtCore.QSize(400, 400)
pixmap = QtGui.QPixmap(path)

pixmap = pixmap.scaled(low_rez)

I then increase the resolution back to normal. The default scale uses FastTransformation

1
pixmap = pixmap.scaled(high_rez)

This is the result:

pixmap-not-smooth

The Solution

I’ve searched many forums and people were all saying: enable the SmoothTransformation, I tried but didn’t work.

Later on I found out that the Qt translation to Python has a mis-match keyword argument: so instead of transformMode=Qt.SmoothTransformation, it should actually be mode=Qt.SmoothTransformation

So here’s the solution:

1
2
3
4
5
pixmap = pixmap.scaled(
high_rez,
aspectRatioMode=QtCore.Qt.KeepAspectRatio,
mode=QtCore.Qt.SmoothTransformation
)

and result:

pixmap-smooth

Extra

I also found post saying it might be some settings with the QPainter, but it is not the issue for me.

1
2
3
4
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True)
painter.drawPixmap(self.pixmap)

Reference

Qt Documentation - QPixmap Class