Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

111 lignes
2.4 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)
  9. {
  10. setFlags(QGraphicsItem::ItemIsMovable |
  11. QGraphicsItem::ItemIsSelectable |
  12. QGraphicsItem::ItemSendsGeometryChanges);
  13. }
  14. QRectF Item::boundingRect() const
  15. {
  16. return QRectF(-22, -15, 44, 30);
  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::MenuActions(QMenu *menu)
  53. {
  54. menu->addAction("复制");
  55. menu->addAction("删除");
  56. menu->addAction("对象");
  57. }
  58. void Item::addMenuActions(QMenu *menu)
  59. {
  60. Q_UNUSED(menu);
  61. }
  62. void Item::handleMenuAction(QAction *action)
  63. {
  64. if (action->text() == "复制") {
  65. emit requestCopy(this);
  66. }
  67. if (action->text() == "删除") {
  68. emit requestDelete(this);
  69. }
  70. if (action->text() == "对象"){
  71. emit requestBindRegister(this);
  72. }
  73. }
  74. QVariant Item::itemChange(GraphicsItemChange change, const QVariant &value)
  75. {
  76. if (change == QGraphicsItem::ItemPositionChange) {
  77. for (Connection* conn : connections_)
  78. conn->updatePosition();
  79. }
  80. return QGraphicsObject::itemChange(change, value);
  81. }
  82. void Item::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
  83. {
  84. QMenu menu;
  85. // 创建菜单
  86. MenuActions(&menu);
  87. addMenuActions(&menu);
  88. // 执行菜单
  89. QAction *selected = menu.exec(event->screenPos());
  90. // 处理菜单动作
  91. if (selected) {
  92. handleMenuAction(selected);
  93. }
  94. }