如何实时返回鼠标坐标?

6 python pyqt python-3.x qt5 pyqt5

我是 PyQt 的新手,我正在尝试使用它来创建一个可以实时返回鼠标位置的小部件。

这是我所拥有的:

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, 
    QPushButton, QApplication)
from PyQt5.QtGui import QFont    

class MouseTracker(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setMouseTracking(True)
        self.installEventFilter(self)

    def initUI(self):        
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Mouse Tracker')    
        self.show()

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            event.buttons() == QtCore.Qt.NoButton):
                pos = event.pos()
                print('Mouse coords: ( %d : %d )' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MouseTracker()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

我对如何使这项工作感到困惑。我将鼠标跟踪设置为 True,但我不确定如何应用事件过滤器。有什么帮助吗?

eyl*_*esc 5

QMouseEvent 函数必须实现,因为它是在鼠标移动时执行的。

import sys
from PyQt5.QtWidgets import (QApplication, QLabel, QWidget)


class MouseTracker(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setMouseTracking(True)

    def initUI(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Mouse Tracker')
        self.label = QLabel(self)
        self.label.resize(200, 40)
        self.show()

    def mouseMoveEvent(self, event):
        self.label.setText('Mouse coords: ( %d : %d )' % (event.x(), event.y()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MouseTracker()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明