1. 程式人生 > 其它 >如何在pyqt中使用 QGraphicsView 實現圖片檢視器

如何在pyqt中使用 QGraphicsView 實現圖片檢視器

前言

在 PyQt 中可以使用很多方式實現照片檢視器,最樸素的做法就是重寫 QWidgetpaintEvent()mouseMoveEvent 等事件,但是如果要在影象上多新增一些形狀,那麼在對影象進行縮放旋轉等仿射變換時需要對這些形狀也這些變換,雖然不難,但是從頭實現這些變換還有形狀還是挺討厭的。好在 Qt 提供了圖形檢視框架,關於這個框架的基本使用可以參見 《快速掌握PyQt5》第三十四章 圖形檢視框架,下面進入正題。

實現方式

一個最基本的照片檢視器應該具有以下功能:

  • 載入影象
  • 縮放影象
  • 在視窗尺寸小於影象時允許拖拽影象

載入影象可以使用 QGraphicsPixmapItem

來解決,縮放影象使用 QGraphicsViewscale(sx, sy) 解決,移動影象只需將 QGraphicsViewdragMode 設定為 QGraphicsView.ScrollHandDrag 即可。因為常常使用滑鼠滾輪來縮放影象,所以還需要重寫重寫以下 QGraphicsViewwheelEvent

實際上由於視窗的縮放導致視口大小變化,還有一些細枝末節需要處理。具體程式碼如下:

# coding:utf-8
import sys

from PyQt5.QtCore import QRect, QRectF, QSize, Qt
from PyQt5.QtGui import QPainter, QPixmap, QWheelEvent
from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsPixmapItem,
                             QGraphicsScene, QGraphicsView)


class ImageViewer(QGraphicsView):
    """ 圖片檢視器 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.zoomInTimes = 0
        self.maxZoomInTimes = 22

        # 建立場景
        self.graphicsScene = QGraphicsScene()

        # 圖片
        self.pixmap = QPixmap(r'D:\hzz\圖片\硝子\硝子 (2).jpg')
        self.pixmapItem = QGraphicsPixmapItem(self.pixmap)
        self.displayedImageSize = QSize(0, 0)

        # 初始化小部件
        self.__initWidget()

    def __initWidget(self):
        """ 初始化小部件 """
        self.resize(1200, 900)

        # 隱藏滾動條
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # 以滑鼠所在位置為錨點進行縮放
        self.setTransformationAnchor(self.AnchorUnderMouse)

        # 平滑縮放
        self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.setRenderHints(QPainter.Antialiasing |
                            QPainter.SmoothPixmapTransform)

        # 設定場景
        self.graphicsScene.addItem(self.pixmapItem)
        self.setScene(self.graphicsScene)

    def wheelEvent(self, e: QWheelEvent):
        """ 滾動滑鼠滾輪縮放圖片 """
        if e.angleDelta().y() > 0:
            self.zoomIn()
        else:
            self.zoomOut()

    def resizeEvent(self, e):
        """ 縮放圖片 """
        super().resizeEvent(e)

        if self.zoomInTimes > 0:
            return

        # 調整圖片大小
        ratio = self.__getScaleRatio()
        self.displayedImageSize = self.pixmap.size()*ratio
        if ratio < 1:
            self.fitInView(self.pixmapItem, Qt.KeepAspectRatio)
        else:
            self.resetTransform()

    def setImage(self, imagePath: str):
        """ 設定顯示的圖片 """
        self.resetTransform()

        # 重新整理圖片
        self.pixmap = QPixmap(imagePath)
        self.pixmapItem.setPixmap(self.pixmap)

        # 調整圖片大小
        self.setSceneRect(QRectF(self.pixmap.rect()))
        ratio = self.__getScaleRatio()
        self.displayedImageSize = self.pixmap.size()*ratio
        if ratio < 1:
            self.fitInView(self.pixmapItem, Qt.KeepAspectRatio)

    def resetTransform(self):
        """ 重置變換 """
        super().resetTransform()
        self.zoomInTimes = 0
        self.__setDragEnabled(False)

    def __isEnableDrag(self):
        """ 根據圖片的尺寸決定是否啟動拖拽功能 """
        v = self.verticalScrollBar().maximum() > 0
        h = self.horizontalScrollBar().maximum() > 0
        return v or h

    def __setDragEnabled(self, isEnabled: bool):
        """ 設定拖拽是否啟動 """
        self.setDragMode(
            self.ScrollHandDrag if isEnabled else self.NoDrag)

    def __getScaleRatio(self):
        """ 獲取顯示的影象和原始影象的縮放比例 """
        if self.pixmap.isNull():
            return 1

        pw = self.pixmap.width()
        ph = self.pixmap.height()
        rw = min(1, self.width()/pw)
        rh = min(1, self.height()/ph)
        return min(rw, rh)

    def fitInView(self, item: QGraphicsItem, mode=Qt.KeepAspectRatio):
        """ 縮放場景使其適應視窗大小 """
        super().fitInView(item, mode)
        self.displayedImageSize = self.__getScaleRatio()*self.pixmap.size()
        self.zoomInTimes = 0

    def zoomIn(self, viewAnchor=QGraphicsView.AnchorUnderMouse):
        """ 放大影象 """
        if self.zoomInTimes == self.maxZoomInTimes:
            return

        self.setTransformationAnchor(viewAnchor)

        self.zoomInTimes += 1
        self.scale(1.1, 1.1)
        self.__setDragEnabled(self.__isEnableDrag())

        # 還原 anchor
        self.setTransformationAnchor(self.AnchorUnderMouse)

    def zoomOut(self, viewAnchor=QGraphicsView.AnchorUnderMouse):
        """ 縮小影象 """
        if self.zoomInTimes == 0 and not self.__isEnableDrag():
            return

        self.setTransformationAnchor(viewAnchor)

        self.zoomInTimes -= 1

        # 原始影象的大小
        pw = self.pixmap.width()
        ph = self.pixmap.height()

        # 實際顯示的影象寬度
        w = self.displayedImageSize.width()*1.1**self.zoomInTimes
        h = self.displayedImageSize.height()*1.1**self.zoomInTimes

        if pw > self.width() or ph > self.height():
            # 在視窗尺寸小於原始影象時禁止繼續縮小影象比視窗還小
            if w <= self.width() and h <= self.height():
                self.fitInView(self.pixmapItem)
            else:
                self.scale(1/1.1, 1/1.1)
        else:
            # 在視窗尺寸大於影象時不允許縮小的比原始影象小
            if w <= pw:
                self.resetTransform()
            else:
                self.scale(1/1.1, 1/1.1)

        self.__setDragEnabled(self.__isEnableDrag())

        # 還原 anchor
        self.setTransformationAnchor(self.AnchorUnderMouse)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = ImageViewer()
    w.show()
    sys.exit(app.exec_())

測試

來看一下實際的使用效果: