3
votes

Briefly I want to track mouse coordinate over a QGraphicsView.

This answer works well for a QLabel object, but not works as expected when I switch to QGraphicsView as follows:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)

        self.graphicsView.setMouseTracking(True)
        self.graphicsView.installEventFilter(self)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsView)


    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.graphicsView):
            pos = event.pos()
            print('mouse move: (%d, %d)' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())

Specifically, it seems like that the event is caught only when my cursor moves accross the border of the QGraphicsView (the black lines).

enter image description here

Could anyone tell me why and is there any better solutions?

2

2 Answers

4
votes

For certain widgets, you need to use its viewport instead:

    self.graphicsView.viewport().installEventFilter(self)
    ...

def eventFilter(self, source, event):
    if (event.type() == QtCore.QEvent.MouseMove and
        source is self.graphicsView.viewport()):
    ...
2
votes

An alternative is to override mouseMoveEvent(event) of QGraphicsView directly.

Example:

from PySide import QtGui

class MyGraphicsView(QtGui.QGraphicsView):

    def __init__(self, parent):
        QtGui.QGraphicsView.__init__(self, parent)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, event):
        print('mouseMoveEvent: pos {}'.format(event.pos()))

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = MyGraphicsView(self)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsView)

app = QtGui.QApplication([])
window = Window()
window.show()
window.resize(200, 100)
app.exec_()