移动显示的 PyQt5 场景

Move the displayed PyQt5 scene

我在 QGraphicsView 对象中有一个 QGraphicSscene。在我的场景中,您可以绘制 ROI,因此我始终跟踪鼠标位置。由于对象通常不是很大,您可以放大它们,我想在鼠标位于显示场景的边缘时移动显示的场景部分。使用 event.scenePos() 我得到了我的鼠标指针的位置,但是我如何检查我是否在场景的边缘?

我的代码中的放大和缩小功能如下:

def zoomIn(self):
    self.view.scale(1.1, 1.1)
    # some other stuff

def zoomOut(self):
    # The initial zoom is always adapted to an image so that it is always larger or equal to the 
    # size of the GraphicsViews Object (therefore the image fills all areas). 
    if.self.currentZoom > 1: 
        self.view.scale(0.9, 0.9)
        # some other stuff

要确定一个点是否在边缘上,您必须验证该点是否在 QGraphicsView 视口的矩形内部,但在一个较小的矩形之外,该矩形从前一个矩形在所有边缘上位移了一些像素:

import sys

from PyQt5 import QtCore, QtGui, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        scene = QtWidgets.QGraphicsScene(self)
        self.view = QtWidgets.QGraphicsView(scene)
        self.setCentralWidget(self.view)

        self.view.viewport().setMouseTracking(True)
        self.view.scene().installEventFilter(self)

    def eventFilter(self, obj, event):
        if (
            obj is self.view.scene()
            and event.type() == QtCore.QEvent.GraphicsSceneMouseMove
        ):
            vp = self.view.mapFromScene(event.scenePos())
            if self.check_if_the_point_is_on_the_edge(vp, delta=10):
                print("on the border", event.scenePos())
        return super().eventFilter(obj, event)

    def check_if_the_point_is_on_the_edge(self, point, delta=1):
        rect = self.view.viewport().rect()
        internal_rect = rect.adjusted(delta, delta, -delta, -delta)
        return rect.contains(point) and not internal_rect.contains(point)


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.show()
    w.resize(640, 480)

    sys.exit(app.exec_())