【问题标题】:How to return mouse coordinates in realtime?如何实时返回鼠标坐标?
【发布时间】:2017-06-01 00:23:35
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x pyqt qt5 pyqt5


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 2012-02-11
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多