Zoom in on the current mouse position of a QGraphicsView without losing quality
-
I know this is possible by using the scale method of the QGraphicsView and setting the anchor using
setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
. However, doing so would result to the image quality being compromised when zooming.So what I did instead is to scale the pixmap, and set it as the QGraphicsPixmapItem of the scene. To zoom in on the current mouse position, I use the mapToScene method and position of the wheel event, but this is still not as smooth as the "traditional" implementation. Any idea how I can improve this behavior?
Code:
class Zoom_View(QGraphicsView): def __init__(self): super().__init__() self.scene = QGraphicsScene() self.setScene(self.scene) self.pix_map = QPixmap("path/to/file") self.pix_map_item = self.scene.addPixmap(self.pix_map) self.global_factor = 1 def scaleImage(self, factor): _pixmap = self.pix_map.scaledToHeight(int(factor*self.viewport().geometry().height()), Qt.SmoothTransformation) self.pix_map_item.setPixmap(_pixmap) self.scene.setSceneRect(QRectF(_pixmap.rect())) def wheelEvent(self, event): factor = 1.5 if QApplication.keyboardModifiers() == Qt.ControlModifier: view_pos = event.pos() scene_pos = self.mapToScene(view_pos) self.centerOn(scene_pos) if event.angleDelta().y() > 0 and self.global_factor < 20: self.global_factor *= factor self.scaleImage(self.global_factor) elif event.angleDelta().y() < 0 and self.global_factor > 0.2: self.global_factor /= factor self.scaleImage(self.global_factor) else: return super().wheelEvent(event)
-
Hi and welcome to devnet,
What about scaling the view rather than the pixmap ?
See this wiki article for a possible implementation.
-
@SGaist said in Zoom in on the current mouse position of a QGraphicsView without losing quality:
What about scaling the view rather than the pixmap ?
Hello @SGaist do you mean using QGraphicsView
scale
method? I have already tried that and it zooms in properly on the current mouse position when I set the anchor toAnchorUnderMouse
. However the quality of the image is awful since thescale
method has no smooth transformation mode -
By the way, what is the resolution of your original image ?
-
Depending on your end goal, you might want to consider using a library like OpenCV to do the zooming part and Qt to display the result.