Keren Meron
Keren Meron

Reputation: 139

Zoom QImage on QPixmap in QLabel

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)

Upvotes: 1

Views: 5147

Answers (1)

michael
michael

Reputation: 55

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

Upvotes: 2

Related Questions