#ifndef CUSTOMGRAPHICS_H #define CUSTOMGRAPHICS_H #include #include // 只需要前向声明,因为头文件中只用到了指针 class QPainter; class QGraphicsSceneMouseEvent; class QGraphicsSceneContextMenuEvent; class QGraphicsSceneHoverEvent; enum class ComponentType { Button, Indicator }; // HMI组件基类 class HmiComponent : public QGraphicsObject { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor) // 当前颜色(默认使用 OFF 状态) Q_PROPERTY(QString componentName READ componentName WRITE setComponentName) // 新增address属性 Q_PROPERTY(int address READ address WRITE setAddress) signals: void selected(HmiComponent* item); void copyRequested(HmiComponent* item); void deleteRequested(HmiComponent* item); // 添加信号用于改变状态颜色 void changeOnColorRequested(HmiComponent* item); void changeOffColorRequested(HmiComponent* item); public: explicit HmiComponent(QGraphicsItem *parent = nullptr); void setColor(const QColor& color); // 当前显示颜色 QColor color() const; void setComponentName(const QString& name); QString componentName() const; // 设置 ON / OFF 状态颜色 void setOnColor(const QColor& color); void setOffColor(const QColor& color); QColor onColor() const; QColor offColor() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; // 地址相关 void setAddress(int address); int address() const; void setSize(double width, double height); QSizeF size() const { return QSizeF(m_width, m_height); } protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override; void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override; virtual void paintShape(QPainter* painter) = 0; void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; protected: QColor m_color; // 当前显示颜色(编辑器中为 OFF) QColor m_onColor = Qt::green; QColor m_offColor; QString m_componentName; int m_address = 0; // 新增尺寸成员 double m_width = 65.0; double m_height = 30.0; enum ResizeHandle { None, BottomRight }; // 缩放控制点位置 ResizeHandle m_resizeHandle = None; bool m_resizing = false; QPointF m_resizeStartPos; QSizeF m_resizeStartSize; }; // 按钮类 class HmiButton : public HmiComponent { Q_OBJECT public: HmiButton(QGraphicsItem *parent = nullptr); QRectF boundingRect() const override; void setSize(double width, double height); // 新增状态标志,true = ON,false = OFF bool isOn() const; void setOn(bool on); signals: void stateChanged(bool on); protected: void paintShape(QPainter *painter) override; void mousePressEvent(QGraphicsSceneMouseEvent *event) override; private: bool m_isOn = false; // 默认OFF }; // 指示灯类 class HmiIndicator : public HmiComponent { public: HmiIndicator(QGraphicsItem *parent = nullptr); QRectF boundingRect() const override; void setSize(double width, double height); protected: void paintShape(QPainter *painter) override; }; #endif // CUSTOMGRAPHICS_H