DraggableLine.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "DraggableLine.h"
  2. #include <QGraphicsSceneMouseEvent>
  3. #include <QPainter>
  4. #include <QDebug>
  5. #include <QGraphicsScene>
  6. void DraggableLine::mousePressEvent(QGraphicsSceneMouseEvent* event) {
  7. QPointF pos = event->pos(); // 获取相对于项的坐标
  8. QLineF currentLine = line();
  9. if (isNearPoint(pos, currentLine.p1())) {
  10. draggingStart = true;
  11. offset = currentLine.p1() - pos;
  12. }
  13. else if (isNearPoint(pos, currentLine.p2())) {
  14. draggingEnd = true;
  15. offset = currentLine.p2() - pos;
  16. }
  17. else {
  18. // 如果没有点击控制点,可以处理其他逻辑或忽略
  19. QGraphicsLineItem::mousePressEvent(event);
  20. return;
  21. }
  22. event->accept(); // 标记事件已处理
  23. }
  24. void DraggableLine::mouseMoveEvent(QGraphicsSceneMouseEvent* event) {
  25. if (draggingStart || draggingEnd) {
  26. QLineF currentLine = line();
  27. QPointF newPos = event->pos() + offset; // 计算新的端点位置
  28. if (draggingStart) {
  29. currentLine.setP1(newPos);
  30. }
  31. else {
  32. currentLine.setP2(newPos);
  33. }
  34. setLine(currentLine); // 更新线段
  35. scene()->update(); // 请求重绘
  36. event->accept();
  37. }
  38. else {
  39. QGraphicsLineItem::mouseMoveEvent(event);
  40. }
  41. }
  42. void DraggableLine::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) {
  43. draggingStart = false;
  44. draggingEnd = false;
  45. QLineF currentLine = line();
  46. qDebug() << "线段长度:" << currentLine.length();
  47. QGraphicsLineItem::mouseReleaseEvent(event);
  48. }
  49. void DraggableLine::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) {
  50. // 先调用基类方法绘制线段
  51. QGraphicsLineItem::paint(painter, option, widget);
  52. // 绘制起点和终点的控制点
  53. painter->setBrush(Qt::red);
  54. painter->drawEllipse(line().p1(), 5, 5);
  55. painter->setBrush(Qt::blue);
  56. painter->drawEllipse(line().p2(), 5, 5);
  57. }
  58. bool DraggableLine::isNearPoint(const QPointF& pos, const QPointF& point) const
  59. {
  60. QLineF line(pos, point);
  61. return (line.length() < 20); // 10像素范围内判定为点击控制点
  62. }