低代码软件搭建自学第2.5天——箭头连线和动态更新


使用 PyQtGraph 实现图形连接器:支持动态拖动和箭头连线


引言

在这篇博客中,使用 PyQtGraphPyQt6 创建一个类似 Visio 的图形编辑器,支持拖动图形、添加矩形和椭圆,以及通过箭头动态连线的功能。

功能总结:

  1. 支持添加矩形和椭圆图形。
  2. 图形可通过鼠标拖动,并动态更新连接的箭头。
  3. 支持 “移动模式” 和 “连线模式” 的切换。
  4. 箭头连线具有真实的起点和终点交点计算。

实现功能的关键点

在实现中,我们利用 PyQtGraph 提供的 GraphicsSceneGraphicsView 作为画布,并结合 PyQt5 的 QGraphicsItem 类自定义了以下组件:

  1. DraggableRectDraggableEllipse:分别实现了可拖动的矩形和椭圆。
  2. ArrowLine:支持动态位置更新的箭头连线。
  3. 模式管理:通过按钮切换图形的移动和连线模式。

代码实现

以下是完整代码:

import pyqtgraph as pg
from pyqtgraph.Qt import QtWidgets, QtGui, QtCore
import math

# 可拖动的矩形类
class DraggableRect(QtWidgets.QGraphicsRectItem):
    def __init__(self, x, y, w, h, color):
        super().__init__(x, y, w, h)
        self.setBrush(QtGui.QBrush(color))
        self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges)
        self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable)
        self.connections = []
        self.move_enabled = True

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemPositionChange:
            if self.move_enabled:
                for arrow in self.connections:
                    arrow.update_position()
            else:
                return self.pos()
        return super().itemChange(change, value)

    def set_movable(self, movable):
        self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable, movable)
        self.move_enabled = movable


# 可拖动的椭圆类
class DraggableEllipse(QtWidgets.QGraphicsEllipseItem):
    def __init__(self, x, y, w, h, color):
        super().__init__(x, y, w, h)
        self.setBrush(QtGui.QBrush(color))
        self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges)
        self.setFlag(QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsMovable)
        self.connections = []
        self.move_enabled = True

    def itemChange(self, change, value):
        if change == QtWidgets.QGraphicsItem.GraphicsItemChange.ItemPositionChange:
            if self.move_enabled:
                for arrow in self.connections:
                    arrow.update_position()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

算法小白(真小白)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值