其他分享
首页 > 其他分享> > 如何在中间鼠标的QGraphicsView中滚动QGraphicsScene?

如何在中间鼠标的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)

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

其次,我无法移动视口外的场景,它到达边缘时停止.

让第二个仍然可以容忍.让它保持原样,但如何计算正确移动的场景的正确偏移移动鼠标,无论它被捕获的位置?

解决方法:

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

标签:qgraphicsview,python,pyqt,mouseevent,qgraphicsscene
来源: https://codeday.me/bug/20190824/1709005.html