如何用鼠标在QGraphicsView中滚动QGraphicsScene?

时间:2015-07-29 13:40:06

标签: python pyqt mouseevent qgraphicsview qgraphicsscene

我使用pyqt4.8和python2.7

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

我创建了鼠标事件功能但移动到奇怪。

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)

首先,场景移动与鼠标的移动不对应。我怀疑是视口的相对大小和场景的责任。以及舞台的规模。

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

让第二个仍然可以容忍。让它保持不变,但如何计算正确移动的场景的正确偏移量,无论它被捕获的位置如何?

1 个答案:

答案 0 :(得分:6)

我的解决方案不是调用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)