12345678910111213141516171819202122232425262728293031323334353637383940 |
- #include "DraggableLine.h"
- void DraggableLine::mousePressEvent(QGraphicsSceneMouseEvent* event) {
- // 判断点击的是起点还是终点
- QPointF clickPos = event->pos();
- if (distance(clickPos, line().p1()) < 10) {
- draggingStart = true;
- } else if (distance(clickPos, line().p2()) < 10) {
- draggingEnd = true;
- }
- }
- void DraggableLine::mouseMoveEvent(QGraphicsSceneMouseEvent* event) {
- if (draggingStart) {
- // 更新起点坐标
- QLineF newLine(event->scenePos(), line().p2());
- setLine(newLine);
- } else if (draggingEnd) {
- // 更新终点坐标
- QLineF newLine(line().p1(), event->scenePos());
- setLine(newLine);
- }
- update();
- }
- void DraggableLine::mouseReleaseEvent(QGraphicsSceneMouseEvent*) {
- draggingStart = draggingEnd = false;
- }
- void DraggableLine::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) {
- painter->setPen(QPen(Qt::blue, 2));
- painter->drawLine(line());
- // 绘制可拖拽端点
- painter->setBrush(Qt::red);
- painter->drawEllipse(line().p1(), 5, 5);
- painter->drawEllipse(line().p2(), 5, 5);
- }
- double DraggableLine::distance(const QPointF& p1, const QPointF& p2) {
- return QLineF(p1, p2).length();
- }
|