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. 控件位置拖动之后,需要通过代码更新位置

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

相关推荐
大学生毕业题目2 小时前
毕业项目推荐:103-基于yolov8/yolov5/yolo11的皮肤癌检测识别系统(Python+卷积神经网络)
人工智能·python·yolo·目标检测·cnn·pyqt·皮肤癌检测
大学生毕业题目2 天前
毕业项目推荐:102-基于yolov8/yolov5/yolo11的行人车辆检测识别系统(Python+卷积神经网络)
人工智能·python·yolo·目标检测·cnn·pyqt·行人车辆检测
大学生毕业题目3 天前
毕业项目推荐:99-基于yolov8/yolov5/yolo11的肾结石检测识别系统(Python+卷积神经网络)
人工智能·python·yolo·目标检测·cnn·pyqt·肾结石检测
深蓝海拓3 天前
PySide6,QEventLoop.exec()的使用
笔记·python·qt·学习·pyqt
深蓝海拓6 天前
PySide6从0开始学习的笔记(二十三)使用QRunnable在线程池中执行临时任务
笔记·python·qt·学习·pyqt
强化试剂6 天前
荧光标记利器 Alkyne-PEG-FITC;FITC-PEG-Alkyne:核心优势与行业价值
python·flask·pyqt·scipy
深蓝海拓10 天前
PySide6从0开始学习的笔记(二十二) 几种封装信号传递内容的方法
笔记·python·qt·学习·pyqt
赤鸢QAQ10 天前
PySide6批量创建控件
python·qt·pyqt
深蓝海拓12 天前
PySide6之QListWidget 学习
笔记·python·qt·学习·pyqt