这里写自定义目录标题
- 前言:
- 基础夯实:
- 成功效果展示:
- 失败效果展示:
- 核心代码:
前言:
对之前箭头没有成功绘制的补充,因为没有直接的箭头项,所以需要自己进行绘制
基础夯实:
可以直接看,建议看一下之前的绘制过程
在控件graphicsView中实现绘图功能(一)
在控件graphicsView中实现绘图功能(二)
在控件graphicsView中实现绘图功能(三)
成功效果展示:
失败效果展示:
核心代码:
#include "CustomGraphicsView.h"
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <cmath>
#include <QPolygonF>CustomGraphicsView::CustomGraphicsView(QWidget *parent): QGraphicsView(parent), isDrawing(false), arrowPolygonItem(nullptr),arrowLineItem(nullptr)
{const double arrowSize = 10.0;
}void CustomGraphicsView::setDrawMode(DrawMode mode)
{currentDrawMode = mode;
}void CustomGraphicsView::mousePressEvent(QMouseEvent *event)
{if (event->button() == Qt::LeftButton) {isDrawing = true;startPoint = mapToScene(event->pos());endPoint = startPoint; // Initialize endPoint to startPointswitch (currentDrawMode) {case ArrowsMode:arrowPolygonItem = nullptr;arrowLineItem = nullptr; // 重置箭头直线项break;default:break;}emit mouseClicked(event->pos());}QGraphicsView::mousePressEvent(event);
}void CustomGraphicsView::mouseMoveEvent(QMouseEvent *event)
{if (isDrawing) {endPoint = mapToScene(event->pos());switch (currentDrawMode) {case ArrowsMode: {// 绘制直线if (!arrowLineItem) {arrowLineItem = scene()->addLine(QLineF(startPoint, endPoint), QPen(Qt::green));} else {arrowLineItem->setLine(QLineF(startPoint, endPoint));}// 绘制箭头头部if (!arrowPolygonItem) {// 计算从起点到终点的角度double angle = std::atan2(endPoint.y() - startPoint.y(), endPoint.x() - startPoint.x());// 调整角度,确保箭头是锐角(15度)double arrowAngle = M_PI - 15.0 / 180.0 * M_PI; // 15度角// 计算箭头的三个顶点QPointF arrowP1 = QPointF(endPoint.x() + 10.0 * std::cos(angle + arrowAngle), endPoint.y() + 10.0 * std::sin(angle + arrowAngle));QPointF arrowP2 = endPoint;QPointF arrowP3 = QPointF(endPoint.x() + 10.0 * std::cos(angle - arrowAngle), endPoint.y() + 10.0 * std::sin(angle - arrowAngle));QPolygonF arrowHeadPolygon;arrowHeadPolygon << arrowP1 << arrowP2 << arrowP3;arrowPolygonItem = scene()->addPolygon(arrowHeadPolygon, QPen(Qt::green), QBrush(Qt::green));} else {double angle = std::atan2(endPoint.y() - startPoint.y(), endPoint.x() - startPoint.x());double arrowAngle = M_PI - 15.0 / 180.0 * M_PI; // 15度角QPointF arrowP1 = QPointF(endPoint.x() + 10.0 * std::cos(angle + arrowAngle), endPoint.y() + 10.0 * std::sin(angle + arrowAngle));QPointF arrowP2 = endPoint;QPointF arrowP3 = QPointF(endPoint.x() + 10.0 * std::cos(angle - arrowAngle), endPoint.y() + 10.0 * std::sin(angle - arrowAngle));QPolygonF arrowHeadPolygon;arrowHeadPolygon << arrowP1 << arrowP2 << arrowP3;arrowPolygonItem->setPolygon(arrowHeadPolygon);}break;}default:break;}}emit mouseMoved(event->pos());
}void CustomGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{if (event->button() == Qt::LeftButton && isDrawing) {isDrawing = false;}emit mouseReleased(event->pos());QGraphicsView::mouseReleaseEvent(event);
}