pyqt5显示原图不改变大小,且可以通过滚轮缩放图片
时间: 2024-03-21 12:42:22 浏览: 17
如果您想要在PyQt5中显示原图并允许用户通过滚轮缩放图片,可以使用QGraphicsView和QGraphicsScene。以下是示例代码:
```python
import sys
from PyQt5.QtGui import QPixmap, QWheelEvent
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene
class ImageViewer(QGraphicsView):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建一个QGraphicsScene
self.scene = QGraphicsScene(self)
# 加载图片
pixmap = QPixmap('image.png')
# 将图片添加到QGraphicsScene中
self.scene.addPixmap(pixmap)
# 将QGraphicsScene设置为视图的场景
self.setScene(self.scene)
# 设置视图的大小策略为“保持大小”
self.setResizeAnchor(QGraphicsView.AnchorViewCenter)
self.setTransformationAnchor(QGraphicsView.AnchorViewCenter)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setRenderHint(QGraphicsView.SmoothPixmapTransform)
self.setRenderHint(QGraphicsView.HighQualityAntialiasing)
self.setRenderHint(QGraphicsView.NonCosmeticDefaultPen)
def wheelEvent(self, event: QWheelEvent) -> None:
# 改变视图的缩放级别
scale_factor = 1.15
if event.angleDelta().y() > 0:
self.scale(scale_factor, scale_factor)
else:
self.scale(1 / scale_factor, 1 / scale_factor)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = ImageViewer()
ex.show()
sys.exit(app.exec_())
```
这个例子中,我们创建了一个名为ImageViewer的QGraphicsView,并在其中创建了一个QGraphicsScene。我们将图片加载到QGraphicsScene中,并将QGraphicsScene设置为视图的场景。然后,我们将视图的大小策略设置为“保持大小”,以确保它不会改变图片的大小。我们重写了wheelEvent()方法,以便用户可以通过滚轮缩放图片。最后,我们将视图显示在屏幕上。
注意,我们使用了一些额外的参数来将视图设置为更好的质量,比如平滑的像素变换、高质量的抗锯齿和默认的非化妆笔。这些参数是可选的,您可以根据自己的需要进行设置。