pyqt5移动鼠标显示坐标的方法

yipeiwu_com7年前Python基础

如下所示:

# -*- 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),那么你只有按住鼠标左键移动的时候才会获取值。所以,把想获取的地方都加上吧。

以上这篇pyqt5移动鼠标显示坐标的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python从入门到精通 windows安装python图文教程

python从入门到精通 windows安装python图文教程

Python的官方介绍是: Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性...

Flask SQLAlchemy一对一,一对多的使用方法实践

Flask-SQLAlchemy安装和建表操作请参考这里。 复制代码 代码如下:# Role表class Role(db.Model):    id=db...

Python any()函数的使用方法

描述: 如果iterable的任何元素为true,则返回true。如果iterable为空,则返回false。相当于: def any(iterable): for elemen...

Python处理字符串之isspace()方法的使用

 isspace()方法检查字符串是否包含空格。 语法 以下是isspace()方法的语法: str.isspace() 参数   &nbs...

python访问系统环境变量的方法

本文实例讲述了python访问系统环境变量的方法。分享给大家供大家参考。具体如下: #-------------------------------- # Name: en...