GraphicsRectItem.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include "GraphicsRectItem.h"
  2. GraphicsRectItem::GraphicsRectItem(const QRect & rect ,QGraphicsItem *parent)
  3. :GraphicsItem(parent)
  4. ,m_width(rect.width())
  5. ,m_height(rect.height())
  6. ,m_isSquare(false)
  7. {
  8. m_rect =rect;
  9. m_handles.reserve(SizeHandleRect::None);
  10. for (int i = SizeHandleRect::LeftTop; i <= SizeHandleRect::Left; ++i) {
  11. SizeHandleRect *shr = new SizeHandleRect(this, static_cast<SizeHandleRect::Direction>(i), this);
  12. m_handles.push_back(shr);
  13. }
  14. updateGeometry();
  15. setFlag(QGraphicsItem::ItemIsMovable, true);
  16. setFlag(QGraphicsItem::ItemIsSelectable, true);
  17. setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
  18. this->setAcceptHoverEvents(true);
  19. }
  20. QRectF GraphicsRectItem::boundingRect() const
  21. {
  22. return rect();
  23. }
  24. QPainterPath GraphicsRectItem::shape() const
  25. {
  26. QPainterPath path;
  27. path.addRect(boundingRect());
  28. return qt_graphicsItem_shapeFromPath(path,_pen);
  29. }
  30. void GraphicsRectItem::resizeTo(SizeHandleRect::Direction dir, const QPointF &point)
  31. {
  32. QPointF local = mapFromScene(point);
  33. QString dirName;
  34. QRect delta =m_rect.toRect();
  35. switch (dir) {
  36. case SizeHandleRect::LeftTop:
  37. delta.setTopLeft(local.toPoint());
  38. break;
  39. case SizeHandleRect::Top:
  40. dirName = "Top";
  41. delta.setTop(local.y());
  42. break;
  43. case SizeHandleRect::RightTop:
  44. dirName = "RightTop";
  45. delta.setTopRight(local.toPoint());
  46. break;
  47. case SizeHandleRect::Left:
  48. dirName = "Left";
  49. delta.setLeft(local.x());
  50. break;
  51. case SizeHandleRect::Right:
  52. dirName = "Rigth";
  53. delta.setRight(local.x());
  54. break;
  55. case SizeHandleRect::LeftBottom:
  56. dirName = "LeftBottom";
  57. delta.setBottomLeft(local.toPoint());
  58. break;
  59. case SizeHandleRect::Bottom:
  60. dirName = "Bottom";
  61. delta.setBottom(local.y());
  62. break;
  63. case SizeHandleRect::RightBottom:
  64. dirName = "RightBottom";
  65. delta.setBottomRight(local.toPoint());
  66. break;
  67. default:
  68. break;
  69. }
  70. prepareGeometryChange();
  71. if(m_isSquare)
  72. {
  73. delta.setHeight(delta.width());
  74. }
  75. m_width = delta.width();
  76. m_height = delta.height();
  77. m_rect =delta;
  78. updateGeometry();
  79. }
  80. void GraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  81. {
  82. QPen pen =painter->pen();
  83. pen.setWidth(4);
  84. pen.setColor(m_color);
  85. painter->setPen(pen);
  86. painter->drawRect(rect());
  87. }