PyQt5 QtWidgets.QGraphicsViewのスムーズなズーム

Share on:

スムーズなズームのためにQtWidgets.QGraphicsViewを継承した独自のクラスGraphicsViewを作成します。

1class GraphicsView(QtWidgets.QGraphicsView):
2    def __init__(self, *argv, **keywords):
3        super(GraphicsView, self).__init__(*argv, **keywords)

GraphicsViewクラス内でwheelEventをオーバーライドしてscalingTimeとanimFinishedのメソッドを、wikiを参考にして作成します。

ソースコード

 1# -*- coding: utf-8 -*-
 2import sys
 3from PyQt5 import QtWidgets, QtCore, QtGui
 4class GraphicsView(QtWidgets.QGraphicsView):
 5    def __init__(self, *argv, **keywords):
 6        super(GraphicsView, self).__init__(*argv, **keywords)
 7        
 8        scene = QtWidgets.QGraphicsScene(self)
 9        image = QtGui.QImage('test.png')
10        pixmap = QtGui.QPixmap.fromImage(image)
11        scene.addPixmap(pixmap)
12        self.setScene(scene)
13        self._numScheduledScalings = 0
14    def wheelEvent(self, event):
15        numDegrees = event.angleDelta().y() / 8
16        numSteps = numDegrees / 15
17        self._numScheduledScalings += numSteps
18        if self._numScheduledScalings * numSteps < 0:
19            self._numScheduledScalings = numSteps
20        anim = QtCore.QTimeLine(350, self)
21        anim.setUpdateInterval(20)
22        anim.valueChanged.connect(self.scalingTime)
23        anim.finished.connect(self.animFinished)
24        anim.start()
25    def scalingTime(self, x):
26        factor = 1.0 + float(self._numScheduledScalings) / 300.0
27        self.scale(factor, factor)
28    def animFinished(self):
29        if self._numScheduledScalings > 0:
30            self._numScheduledScalings -= 1
31        else:
32            self._numScheduledScalings += 1
33def main():
34    app = QtWidgets.QApplication(sys.argv)
35    graphics_view = GraphicsView(None)
36    graphics_view.show()
37    app.exec()
38 
39if __name__ == '__main__':
40    main()

関連記事