DraggableLine.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #include "DraggableLine.h"
  2. void DraggableLine::mousePressEvent(QGraphicsSceneMouseEvent* event) {
  3. // 判断点击的是起点还是终点
  4. QPointF clickPos = event->pos();
  5. if (distance(clickPos, line().p1()) < 10) {
  6. draggingStart = true;
  7. } else if (distance(clickPos, line().p2()) < 10) {
  8. draggingEnd = true;
  9. }
  10. }
  11. void DraggableLine::mouseMoveEvent(QGraphicsSceneMouseEvent* event) {
  12. if (draggingStart) {
  13. // 更新起点坐标
  14. QLineF newLine(event->scenePos(), line().p2());
  15. setLine(newLine);
  16. } else if (draggingEnd) {
  17. // 更新终点坐标
  18. QLineF newLine(line().p1(), event->scenePos());
  19. setLine(newLine);
  20. }
  21. update();
  22. }
  23. void DraggableLine::mouseReleaseEvent(QGraphicsSceneMouseEvent*) {
  24. draggingStart = draggingEnd = false;
  25. }
  26. void DraggableLine::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) {
  27. painter->setPen(QPen(Qt::blue, 2));
  28. painter->drawLine(line());
  29. // 绘制可拖拽端点
  30. painter->setBrush(Qt::red);
  31. painter->drawEllipse(line().p1(), 5, 5);
  32. painter->drawEllipse(line().p2(), 5, 5);
  33. }
  34. double DraggableLine::distance(const QPointF& p1, const QPointF& p2) {
  35. return QLineF(p1, p2).length();
  36. }