Capture mouse position outside QMainWindow (without click)

Question:

I tried:

        self.installEventFilter(self)

and:

        desktop= QApplication.desktop()
        desktop.installEventFilter(self)

With:

    def eventFilter(self, source, event):
        if event.type() == QEvent.MouseMove:
            print(event.pos())
        return QMainWindow.eventFilter(self, source, event)

In QMainWindow object but nothing conclusive.
Do you have any idea?

Asked By: Mauricio

||

Answers:

Mouse events are initially handled by the window-manager, which then passes them on to whatever window is in that region of the screen. So if there are no Qt windows in that region, you won’t get any events (including mouse events).

However, it is still possible to track the cursor position via polling:

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    cursorMove = QtCore.pyqtSignal(object)

    def __init__(self):
        super(Window, self).__init__()
        self.cursorMove.connect(self.handleCursorMove)
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(50)
        self.timer.timeout.connect(self.pollCursor)
        self.timer.start()
        self.cursor = None

    def pollCursor(self):
        pos = QtGui.QCursor.pos()
        if pos != self.cursor:
            self.cursor = pos
            self.cursorMove.emit(pos)

    def handleCursorMove(self, pos):
        print(pos)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 500, 200, 200)
    window.show()
    sys.exit(app.exec_())
Answered By: ekhumoro