PyQt5 MouseTracking
时间: 2024-01-13 18:04:04 浏览: 21
PyQt5中的MouseTracking可以跟踪鼠标移动和按钮事件。当启用MouseTracking时,如果鼠标移动,就会自动触发MouseMoveEvent事件,而不需要按下鼠标按钮。
以下是一个简单的例子,演示如何在PyQt5中使用MouseTracking:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setMouseTracking(True) # 启用MouseTracking
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Mouse Tracking')
self.show()
def mouseMoveEvent(self, event):
x = event.x()
y = event.y()
text = f'x: {x}, y: {y}'
self.setWindowTitle(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
sys.exit(app.exec_())
```
在这个例子中,我们创建了一个新的QWidget并启用了MouseTracking。当鼠标移动时,我们重写了mouseMoveEvent()函数来显示鼠标的x和y坐标。
运行程序后,当鼠标移动时,窗口标题将显示鼠标的x和y坐标。