如何实时返回鼠标坐标? [英] How to return mouse coordinates in realtime?

查看:19
本文介绍了如何实时返回鼠标坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to PyQt and I'm trying to use it to create a widget that returns the position of the mouse in real time.

这是我所拥有的:

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,但我不确定如何应用事件过滤器.有什么帮助吗?

I'm confused on how to make this work. I set mouse tracking to True but I'm not sure how to apply the event filter. Any help?

推荐答案

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

The QMouseEvent function must be implemented since it is executed when the mouse is moved.

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

这篇关于如何实时返回鼠标坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆