I have the following code:
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QGroupBox, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import sys
class Window(QWidget):
def __init__(self):
super().__init__()
self.imgLabel = QLabel(self)
pixmap = QPixmap("feedreader.jpg")
self.imgLabel.setPixmap(pixmap)
self.imgLabel.setAlignment(Qt.AlignCenter | Qt.AlignCenter)
self.imgLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
scroll = QScrollArea()
scroll.setWidget(self.imgLabel)
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.NoFrame)
self.zoomInButton = QPushButton('Zoom In', self)
self.zoomInButton.clicked.connect(self.onZoomIn)
self.zoomOutButton = QPushButton('Zoom Out', self)
self.zoomOutButton.clicked.connect(self.onZoomOut)
self.buttonGroup = QGroupBox()
vboxButtons = QVBoxLayout()
vboxButtons.addWidget(self.zoomInButton)
vboxButtons.addWidget(self.zoomOutButton)
vboxButtons.addStretch()
self.buttonGroup.setLayout(vboxButtons)
self.hbox = QHBoxLayout()
self.hbox.addWidget(scroll)
self.hbox.addWidget(self.buttonGroup)
self.setLayout(self.hbox)
self.init()
self.show()
def init(self):
self.scaleFactor = 1.0
def onZoomIn(self):
self.scaleImage(1.25)
def onZoomOut(self):
self.scaleImage(0.8)
def scaleImage(self, factor):
self.scaleFactor *= factor
pm = self.imgLabel.pixmap()
x = pm.width() * self.scaleFactor
y = pm.width() * self.scaleFactor
if x > 0 and y > 0:
pm = pm.scaled(x, y, Qt.KeepAspectRatio)
self.imgLabel.setPixmap(pm)
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
Can I implement it better? When I zoom out too much it writes
QPixmap::scaled: Pixmap is a null pixmap
and I cannot zoom in
When I alternate between zoom in and zoom out, the quality of the image is worse and worse.
I took the parameters from here. Are they OK?
pm.width()*self.scaleFactorandpm.height()*self.scaleFactorare both greater than 0. - alec