You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 rivejä
2.6 KiB

  1. #include "item.h"
  2. #include "connection.h"
  3. #include <QMenu>
  4. #include <QPainter>
  5. #include <QStyleOptionGraphicsItem>
  6. #include <QGraphicsSceneContextMenuEvent>
  7. Item::Item(const QString &type, QGraphicsItem *parent)
  8. : QGraphicsObject(parent), type_(type), registerId_("")
  9. {
  10. setFlags(QGraphicsItem::ItemIsMovable |
  11. QGraphicsItem::ItemIsSelectable |
  12. QGraphicsItem::ItemSendsGeometryChanges);
  13. }
  14. QRectF Item::boundingRect() const
  15. {
  16. return QRectF(-22, -12, 44, 32);
  17. }
  18. QPointF Item::anchorPos(AnchorType type) const
  19. {
  20. // 对于"按钮"和"指示灯"类型,返回无效坐标
  21. if (type_ == "按钮" || type_ == "指示灯") {
  22. return QPointF(std::numeric_limits<qreal>::quiet_NaN(),
  23. std::numeric_limits<qreal>::quiet_NaN());
  24. }
  25. // 其他类型正常返回连接点位置
  26. return mapToScene(type == Left ? QPointF(-18, 0) : QPointF(18, 0));
  27. }
  28. void Item::addConnection(Connection* conn)
  29. {
  30. // 对于"按钮"和"指示灯"类型,不允许添加连接
  31. if (type_ == "按钮" || type_ == "指示灯")
  32. {
  33. return;
  34. }
  35. if (!connections_.contains(conn))
  36. {
  37. connections_.append(conn);
  38. }
  39. }
  40. void Item::removeConnection(Connection* conn)
  41. {
  42. connections_.removeAll(conn);
  43. }
  44. QList<Connection *> Item::connections()
  45. {
  46. return connections_;
  47. }
  48. QString Item::itemType()
  49. {
  50. return type_;
  51. }
  52. void Item::setRegisterValue(const QString &registerId, quint16 value)
  53. {
  54. if (registerId_ == registerId)
  55. {
  56. registerValue_ = value;
  57. update(); // 触发重绘
  58. }
  59. }
  60. void Item::MenuActions(QMenu *menu)
  61. {
  62. menu->addAction("复制");
  63. menu->addAction("删除");
  64. menu->addAction("对象");
  65. }
  66. void Item::addMenuActions(QMenu *menu)
  67. {
  68. Q_UNUSED(menu);
  69. }
  70. void Item::handleMenuAction(QAction *action)
  71. {
  72. if (action->text() == "复制") {
  73. emit requestCopy(this);
  74. }
  75. if (action->text() == "删除") {
  76. emit requestDelete(this);
  77. }
  78. if (action->text() == "对象"){
  79. emit requestBindRegister(this);
  80. }
  81. }
  82. QVariant Item::itemChange(GraphicsItemChange change, const QVariant &value)
  83. {
  84. if (change == QGraphicsItem::ItemPositionChange) {
  85. for (Connection* conn : connections_)
  86. conn->updatePosition();
  87. }
  88. return QGraphicsObject::itemChange(change, value);
  89. }
  90. void Item::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
  91. {
  92. QMenu menu;
  93. // 创建菜单
  94. MenuActions(&menu);
  95. addMenuActions(&menu);
  96. // 执行菜单
  97. QAction *selected = menu.exec(event->screenPos());
  98. // 处理菜单动作
  99. if (selected) {
  100. handleMenuAction(selected);
  101. }
  102. }