如何通过鼠标中键在QGraphicsView 中滚动QGraphicsScene?

How to scrolling QGraphicsScene in QGraphicsView by middle mouse?

我用的是pyqt4.8和python2.7

我创建 QGraphicsView 并插入 QGraphicsScene。场景比视图大,需要滚动。视图有垂直和水平滚动,但我想通过鼠标中键滚动。

我创建了鼠标事件函数但是移动很奇怪。

def mousePressEvent(self, event):
    self.__mousePressPos = None
    self.__mouseMovePos = None
    if event.button() == Qt.MidButton:
        self.__mousePressPos = event.globalPos()
        self.__mouseMovePos = event.globalPos()
    else:
        super(MyView, self).mousePressEvent(event)

def mouseMoveEvent(self, event):
    if event.buttons() == Qt.MidButton:
        curPos = self.__mousePressPos - self.__mouseMovePos
        self.centerOn(curPos.x(), curPos.y())
        self.__mouseMovePos = globalPos
    else:
        super(MyView, self).mouseMoveEvent(event)

def mouseReleaseEvent(self, event):
    if self.__mousePressPos is not None:
        moved = event.globalPos() - self.__mousePressPos 
        if moved.manhattanLength() > 3:
            event.ignore()
            return
    super(MyView, self).mouseReleaseEvent(event)

首先场景移动与鼠标移动不对应。我怀疑这归咎于视口和场景的相对大小。以及舞台的规模。

其次,我无法将场景移动到视口之外,它会在到达边缘时停止。

让第二还可以忍。让它保持原样,但是如何计算与鼠标移动的场景的正确偏移量,而不管它被捕获到哪里?

我的解决方案是不调用 centerOn 方法,而是使用 QGraphicView 的滚动条:

class MyView(QtGui.QGraphicsView):
    def mousePressEvent(self, event):
        if event.button() == Qt.MidButton: # or Qt.MiddleButton
            self.__prevMousePos = event.pos()
        else:
            super(MyView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MidButton: # or Qt.MiddleButton
            offset = self.__prevMousePos - event.pos()
            self.__prevMousePos = event.pos()

            self.verticalScrollBar().setValue(self.verticalScrollBar().value() + offset.y())
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() + offset.x())
        else:
            super(MyView, self).mouseMoveEvent(event)