3
votes

I use pyqt4.8 and python2.7

I create QGraphicsView and insert QGraphicsScene. Scene bigger than View and need to scroll. View have vertical and horizontal scrolls, but i want to scroll by mouse middle button.

I create mouse event functions but movement to strange.

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)

Firstly the scene movement does not correspond to movement of the mouse. I suspect that the blame for the relative size of the viewport, and the scene. as well as the scale of the stage.

Secondly, I can not move the scene outside the viewport, it stops when it reaches the edge.

let the second can still be tolerated. let it stay as it is, but how to calculate the correct offset to the scene moved in exactly the movement of the mouse, regardless of where it was caught?

1

1 Answers

6
votes

My solution is not to call centerOn method but work with QGraphicView's scrollbars instead:

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)