CSchemeView.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "CSchemeView.h"
  2. #include "CSchemeItem.h"
  3. #include "CRectItem.h"
  4. #include "CLineItem.h"
  5. #include "CTextItem.h"
  6. #include <QGraphicsItem>
  7. #include <QDebug>
  8. CSchemeView::CSchemeView(QWidget *parent) : QGraphicsView(new QGraphicsScene(), parent)
  9. {
  10. setRenderHints(QPainter::Antialiasing); // 抗锯齿
  11. m_group = new QGraphicsItemGroup();
  12. m_group->setFlags(QGraphicsItem::ItemIsMovable);
  13. scene()->addItem(m_group);
  14. setStyleSheet("QGraphicsView {border: 1px solid rgba(0, 0, 0, 0.073);background: rgb(244, 244, "
  15. "255);}");
  16. }
  17. void CSchemeView::addItem(CSchemeItem *item)
  18. {
  19. m_schemes.append(item);
  20. refreshItems();
  21. }
  22. void CSchemeView::clear()
  23. {
  24. qDeleteAll(m_schemes);
  25. m_schemes.clear();
  26. refreshItems();
  27. }
  28. void CSchemeView::refreshItems()
  29. {
  30. for (QGraphicsItem *item : m_items) {
  31. scene()->removeItem(item);
  32. }
  33. m_items.clear();
  34. refreshItemsGeometry();
  35. for (QGraphicsItem *item : m_items) {
  36. m_group->addToGroup(item);
  37. }
  38. QRectF r = m_group->childrenBoundingRect();
  39. setSceneRect(QRectF(QPointF(), r.size()));
  40. }
  41. qreal CSchemeView::maxItemHeight() const
  42. {
  43. qreal h = 0;
  44. for (CSchemeItem *item : m_schemes) {
  45. h = std::max(h, item->borderHeight());
  46. }
  47. return h;
  48. }
  49. void CSchemeView::refreshItemsGeometry()
  50. {
  51. qreal mh = maxItemHeight();
  52. int x = 0;
  53. CSchemeItem *left = nullptr;
  54. for (CSchemeItem *item : m_schemes) {
  55. QRect borderRect = QRect(x, (mh - item->borderHeight()) / 2, item->borderWidth(), item->borderHeight());
  56. item->rectItem()->setRect(borderRect);
  57. QPointF textPos = QPointF(borderRect.left() + (item->borderWidth() - item->textWidth()) / 2,
  58. borderRect.top() + (item->borderHeight() - item->textHeight()) / 2);
  59. item->textItem()->setPos(textPos);
  60. item->rectItem()->setPos(QPoint(0, 0));
  61. if (left != nullptr) {
  62. item->lineItem()->setStartPos(left->rectItem()->centerRight());
  63. item->lineItem()->setEndPos(item->rectItem()->centerLeft());
  64. }
  65. m_items.append(item->rectItem());
  66. x += borderRect.width() + m_hNodeSpace;
  67. left = item;
  68. }
  69. }