# 导入相关模块和包
from PyQt5.Qt import *
import sys
# 重写QWidget类
class MyWindow(QWidget):
# 调用鼠标事件
def mouseMoveEvent(self, me):
label.setText('当前位置{}'.format(me.pos()))
# 找到标签
# label.self.findChild(QLabel)
# 获取鼠标位置
location = me.pos()
# 标签位置跟随鼠标移动
label.move(location)
'''
print('鼠标移动到',me.localPos())
#找到标签
label.self.findChild(QLabel)
#获取鼠标的x,y轴位置
label.move(me.localPos().x(),me.localPos().y())
'''
# 创建应用对象
app = QApplication(sys.argv)
# 创建窗口对象
window = MyWindow()
# 设置窗口大小
window.resize(500, 500)
# 设置窗口标题
window.setWindowTitle('鼠标追踪操作')
# 鼠标跟踪模式设置(按下开始跟踪反之没有按下也开始跟踪)
window.setMouseTracking(True)
# 创建标签对象
label = QLabel(window)
# 设置标签大小
label.resize(400, 100)
# 设置标签内容展示位置
label.setContentsMargins(50, 0, 0, 0)
# 设置
qwidget随主窗口移动_PyQt移动标签
最新推荐文章于 2024-07-25 07:30:00 发布
本文介绍如何在PyQt5中创建一个QLabel,使其能够跟随鼠标移动。通过重写QWidget的mouseMoveEvent方法,获取鼠标位置并更新标签的位置。同时,设置鼠标跟踪模式,创建自定义鼠标图标,提升用户体验。
摘要由CSDN通过智能技术生成