PySide6 Tutorials (三)鼠标移动控件及其位置更新

问题描述

在graphicview中拖拽控件从A位置到B位置 ,但是从B位置再次拖拽 控件的时候,控件依旧从A位置出发,与鼠标不处于同一位置。

解决方案

网上搜了一圈都是收费文章,什么时候开源精神都已经被xxxx用来中间商赚差价了嘛!别人收费我免费,一起进步才不累!

python 复制代码
class RectItem(QtWidgets.QGraphicsRectItem):
    def __init__(self, *args):
        super().__init__(*args)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable)

        self.drag_start_pos = None

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.drag_start_pos = event.pos()  # 记录鼠标点击位置
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            if self.drag_start_pos is not None:
                offset = event.pos() - self.drag_start_pos  # 计算鼠标拖动的偏移量
                new_pos = self.pos() + offset  # 计算新的控件位置
                self.setPos(new_pos)  # 更新控件位置
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.drag_start_pos = None
        super().mouseReleaseEvent(event)
知识点
  1. 控件位置的更新需要用到鼠标的位移
  2. 控件位置拖动之后,需要通过代码更新位置

本文为作者原创,转载需注明出处!!!

相关推荐
深蓝海拓1 天前
PySide6,QCoreApplication::aboutToQuit与QtQore.qAddPostRoutine:退出前后的清理工作
笔记·python·qt·学习·pyqt
深蓝海拓3 天前
PySide6从0开始学习的笔记(二十七) 日志管理
笔记·python·学习·pyqt
极客小云4 天前
【基于AI的自动商品试用系统:不仅仅是虚拟试衣!】
javascript·python·django·flask·github·pyqt·fastapi
进击切图仔5 天前
集成类 pyqt 项目构造流程
pyqt
SNAKEpc121385 天前
PyQtGraph应用(五):k线回放复盘功能实现
python·qt·pyqt
Warren986 天前
Pytest Fixture 到底该用 return 还是 yield?
数据库·oracle·面试·职场和发展·单元测试·pytest·pyqt
石国8 天前
windows10 win10 pyside6 vscode 安装与配置
vscode·pyside6·windows10
深蓝海拓8 天前
PySide6从0开始学习的笔记(二十六) 重写Qt窗口对象的事件(QEvent)处理方法
笔记·python·qt·学习·pyqt
深蓝海拓8 天前
PySide6从0开始学习的笔记(二十五) Qt窗口对象的生命周期和及时销毁
笔记·python·qt·学习·pyqt
SNAKEpc121389 天前
PyQtGraph应用(四):基于PyQtGraph的K线指标图绘制
python·qt·pyqt