PyQt5之QGraphics 003 View基本缩放

下面通过滚动鼠标中键控制QGraphicsView的缩放

"""
QGraphicsView 的基本缩放
By Linyoubiao
2020-03-15
"""

from PyQt5.QtWidgets import (QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtCore import (QPointF, QPoint, QLineF, QLine, QRectF, QRect, Qt)
from PyQt5.QtGui import (QBrush, QPen, QPixmap, QPicture, QImage)
import math


class ImageItem(QGraphicsItem):
    def __init__(self):
        super(ImageItem, self).__init__()
        self.rect = QRectF(QPointF(.0, .0), QPointF(100., 100.))
        self.lena = QImage("c:/pic/lena.jpg")

    def boundingRect(self):
        return self.rect

    def paint(self, painter, option, widget):
        painter.drawImage(QRectF(QPointF(10.0, 10.0), QPointF(50.0, 50.0)), self.lena)
        painter.drawRect(QRectF(QPointF(10.0, 10.0), QPointF(50.0, 50.0)))
        painter.drawText(QRectF(QPointF(10.0, 10.0), QPointF(50.0, 50.0)),
                         Qt.AlignLeft, "Hi\nLena")


class ImageView(QGraphicsView):
    def __init__(self):
        super(ImageView, self).__init__()
        self.scene = QGraphicsScene()
        self.image = ImageItem()
        self.lena = QPixmap("c:/pic/lena.jpg")
        self.setBackgroundBrush(QBrush(self.lena))
        self.scene.addItem(self.image)
        self.setScene(self.scene)

    def wheelEvent(self, event):
        self.scaleView(math.pow(2.0, -event.angleDelta().y() / 240.0))

    def scaleView(self, scaleFactor):
        factor = self.transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width()

        if factor < 0.07 or factor > 100:
            return

        self.scale(scaleFactor, scaleFactor)


if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)

    view = ImageView()
    view.show()

    sys.exit(app.exec_())

 

运行,可以通过滚动鼠标中键缩放,效果如下:

 

PyQt5之QGraphics 003 View基本缩放_第1张图片

PyQt5之QGraphics 003 View基本缩放_第2张图片

你可能感兴趣的:(PyQt5之QGraphics,pyqt)