|
- #include "customgraphics.h"
- #include <QPainter>
- #include <QGraphicsSceneMouseEvent>
- #include <QMenu>
- #include <QGraphicsScene>
-
- // HmiComponent 基类实现
- HmiComponent::HmiComponent(QGraphicsItem *parent) : QGraphicsObject(parent)
- {
- setFlag(QGraphicsItem::ItemIsMovable, true);
- setFlag(QGraphicsItem::ItemIsSelectable, true);
- setAcceptHoverEvents(true);
- }
-
- void HmiComponent::setColor(const QColor& color) {
- if (m_color != color) {
- m_color = color;
- update();
- }
- }
-
- QColor HmiComponent::color() const {
- return m_color;
- }
-
- void HmiComponent::setComponentName(const QString& name) {
- m_componentName = name;
- }
-
- QString HmiComponent::componentName() const {
- return m_componentName;
- }
-
- void HmiComponent::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
- {
- Q_UNUSED(option);
- Q_UNUSED(widget);
- painter->setRenderHint(QPainter::Antialiasing);
-
- paintShape(painter);
-
- if (isSelected()) {
- painter->setBrush(Qt::NoBrush);
- painter->setPen(QPen(Qt::darkRed, 2, Qt::DashLine));
- painter->drawRect(boundingRect());
- }
- }
-
- void HmiComponent::mousePressEvent(QGraphicsSceneMouseEvent *event)
- {
- // 右键不触发选中信号,留给 contextMenuEvent 处理
- if (event->button() == Qt::LeftButton) {
- emit selected(this);
- }
- QGraphicsObject::mousePressEvent(event);
- }
-
- void HmiComponent::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
- {
- // 右键点击时,先清空场景中的其他选中项,然后选中当前项
- scene()->clearSelection();
- setSelected(true);
- emit selected(this); // 同样可以发出选中信号,以便更新属性面板等
-
- QMenu menu;
- QAction *copyAction = menu.addAction("复制");
- QAction *deleteAction = menu.addAction("删除");
-
- // 使用 connect 将菜单动作的触发连接到信号的发射,“复制”和“删除”
- connect(copyAction, &QAction::triggered, this, [this]() {
- emit copyRequested(this);
- });
- connect(deleteAction, &QAction::triggered, this, [this]() {
- emit deleteRequested(this);
- });
-
- // 在鼠标光标位置显示菜单
- menu.exec(event->screenPos());
- }
-
- HmiButton::HmiButton(QGraphicsItem *parent) : HmiComponent(parent)
- {
- m_color = Qt::gray;
- m_componentName = "Button";
- }
-
- QRectF HmiButton::boundingRect() const
- {
- return QRectF(0, 0, 65, 30);
- }
-
- void HmiButton::paintShape(QPainter *painter)
- {
- painter->setPen(Qt::NoPen);
- painter->setBrush(m_color);
- painter->drawRect(boundingRect());
- }
-
- HmiIndicator::HmiIndicator(QGraphicsItem *parent) : HmiComponent(parent)
- {
- m_color = Qt::green;
- m_componentName = "Indicator";
- }
-
- QRectF HmiIndicator::boundingRect() const
- {
- return QRectF(0, 0, 30, 30);
- }
-
- void HmiIndicator::paintShape(QPainter *painter)
- {
- painter->setPen(Qt::NoPen);
- painter->setBrush(m_color);
- painter->drawEllipse(boundingRect());
- }
|