gpt4 book ai didi

python - 如何实时返回鼠标坐标?

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:25 25 4
gpt4 key购买 nike

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

最佳答案

必须实现 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_())

enter image description here

关于python - 如何实时返回鼠标坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41688668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com