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.

117 lines
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)
  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. }
  57. void Item::addMenuActions(QMenu *menu)
  58. {
  59. Q_UNUSED(menu);
  60. }
  61. void Item::handleMenuAction(QAction *action)
  62. {
  63. if (action->text() == "复制") {
  64. emit requestCopy(this);
  65. }
  66. else if (action->text() == "删除") {
  67. emit requestDelete(this);
  68. }
  69. }
  70. QVariant Item::itemChange(GraphicsItemChange change, const QVariant &value)
  71. {
  72. if (change == QGraphicsItem::ItemPositionChange) {
  73. for (Connection* conn : connections_)
  74. conn->updatePosition();
  75. }
  76. return QGraphicsObject::itemChange(change, value);
  77. }
  78. void Item::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
  79. {
  80. // QMenu menu;
  81. // QAction* copyAct = menu.addAction("复制");
  82. // QAction* deleteAct = menu.addAction("删除");
  83. // QAction* selected = menu.exec(event->screenPos());
  84. // if (selected == copyAct) {
  85. // emit requestCopy(this);
  86. // }
  87. // if (selected == deleteAct) {
  88. // emit requestDelete(this);
  89. // }
  90. QMenu menu;
  91. // 创建菜单
  92. MenuActions(&menu);
  93. addMenuActions(&menu);
  94. // 执行菜单
  95. QAction *selected = menu.exec(event->screenPos());
  96. // 处理菜单动作
  97. if (selected) {
  98. handleMenuAction(selected);
  99. }
  100. }