1

I am subclassing QLabel, on which I set QPixmap. I want to zoom into the image displayed in the pixmap (without losing quality). I don't want to see the entire image enlarged, just to zoom in.

I have tried many ways to scale the pixmap, but was unable to get good results. The following code resizes the image, but with very bad quality. What is the right way?

from PyQt5 import QtWidgets, QtCore, QtGui

class ImageLabel(QtWidgets.QLabel):

    def __init__(self, img):
        self.set_image(img)

    def set_image(self, image):
        qimg = QtGui.QPixmap.fromImage(image)
        self._displayed_pixmap = QtGui.QPixmap(qimg)
        # scale image to fit label
        self._displayed_pixmap.scaled(self.width(), self.height(), QtCore.Qt.KeepAspectRatio)
        self.setScaledContents(True)
        self.setMinimumSize(512, 512)
        self.show()

    def zoom_image(self):
        image_size = self._displayed_pixmap.size()
        image_size.setWidth(image_size.width() * 0.9)
        image_size.setHeight(image_size.height() * 0.9)
        self._displayed_pixmap = self._displayed_pixmap.scaled(image_size, QtCore.Qt.KeepAspectRatio)
        self.update()  # call paintEvent()

    def wheelEvent(self, event):
        modifiers = QtWidgets.QApplication.keyboardModifiers()
        if modifiers == QtCore.Qt.ControlModifier:
            self._zoom_image(event.angleDelta().y())

    def paintEvent(self, paint_event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(self.rect(), self._displayed_pixmap)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Keren Meron
  • 139
  • 3
  • 14
  • It is impossible to zoom in on an image with the same quality. Images do not have infinite depth; they have a fixed resolution. Applications like google maps only give the illusion of zooming in with the same quality. They achieve this by using a stack of images with different resolutions. This is obvously a very expensive technique, because the more you zoom in, the more images you need to cover the same area. – ekhumoro Jan 05 '18 at 19:30
  • 1
    PS: you can try the example in [this answer](https://stackoverflow.com/a/35514531/984421) to see if it gives better results than your current code. – ekhumoro Jan 05 '18 at 19:32
  • @ekhumoro QGraphicsScene is very poor with high resolution images:( – Ahmed4end Oct 03 '20 at 17:47

1 Answers1

2

You can try using this: this work for me when I put pictures in PYQT

self._displayed_pixmap.scaled(self.width(), self.height(), QtCore.Qt.SmoothTransformation)

Hope it helps

michael
  • 55
  • 6