pyqt5移动鼠标显示坐标的方法
如下所示:
# -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel) from PyQt5.QtCore import Qt class AppDemo(QMainWindow): def __init__(self): super(AppDemo, self).__init__() self.init_ui() def init_ui(self): self.resize(300, 200) self.setWindowTitle('666') self.label = QLabel(self) self.label.setAlignment(Qt.AlignCenter) self.label.setText('六神花露水') self.label.setGeometry(5, 5, 145, 185) self.label.setMouseTracking(True) self.label_mouse_x = QLabel(self) self.label_mouse_x.setGeometry(155, 5, 80, 30) self.label_mouse_x.setText('x') self.label_mouse_x.setMouseTracking(True) self.label_mouse_y = QLabel(self) self.label_mouse_y.setText('y') self.label_mouse_y.setGeometry(155, 40, 80, 30) self.label_mouse_y.setMouseTracking(True) def mouseMoveEvent(self, event): s = event.windowPos() self.setMouseTracking(True) self.label_mouse_x.setText('X:' + str(s.x())) self.label_mouse_y.setText('Y:' + str(s.y())) def run_it(): app = QApplication(sys.argv) w = AppDemo() w.show() sys.exit(app.exec_()) if __name__ == '__main__': run_it()
特别注意:
在继承QMainwindow的时候,如果你想在窗口中任意位置都获取坐标值的话,就得对每个控件都设置setMouseTracking(True),不然就会出现鼠标在空间上面的时候无法获取坐标值;如果你在重写mouseMoveEvent的时候不加setMouseTracking(True),那么你只有按住鼠标左键移动的时候才会获取值。所以,把想获取的地方都加上吧。
相关推荐
OldBigBrother 2020-11-09
追逐阳光的风 2020-07-04
王磊的程序员之路 2020-05-15
JimyFengqi 2020-02-17
hustlei 2020-02-01
hustlei 2020-01-29
lianback 2020-01-11
追逐阳光的风 2020-01-05
shengge0 2019-12-31
lianback 2019-12-30
Airuio 2019-12-05
hustlei 2011-03-03
OldBigBrother 2019-06-19
Eppley 2019-06-19