捕获 QMainWindow 外的鼠标位置(无需单击)

Capture mouse position outside QMainWindow (without click)

我试过了:

        self.installEventFilter(self)

和:

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

与:

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

在 QMainWindow 对象中,但没有定论。
你有什么想法吗?

鼠标事件最初由 window 管理器处理,然后将它们传递给屏幕该区域中的任何 window。因此,如果该区域中没有 Qt windows,您将不会获得任何事件(包括鼠标事件)。

但是,仍然可以通过轮询跟踪光标位置:

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_())