一、概述
Qt 中没有直接支持绘制直线箭头,所以必须自己用算法画出箭头。
二、算出箭头点的坐标
利用数学函数算出角度,继而算出坐标。
三、代码
// ----------------------------------------
void paintEvent(QPaintEvent *)
{
QPainter painter(this);
QPen pen;
pen.setColor(Qt::black);
painter.setPen(pen);
int lineHStartPos; // 连接线起点水平位置
int lineVStartPos; // 连接线起点垂直位置
int lineHEndPos; // 连接线终点水平位置
int lineVEndPos; // 连接线终点垂直位置
lineHStartPos = 0;
lineVStartPos = 0;
lineHEndPos = 100;
lineVEndPos = 100;
QLineF line(lineHStartPos, lineVStartPos, lineHEndPos, lineVEndPos);
painter.drawLine(line);
// 箭头的两点坐标
double x1, y1, x2, y2;
// 求得箭头两点坐标
CalcVertexes(lineHStartPos, lineVStartPos, lineHEndPos, lineVEndPos, x1, y1, x2, y2);
painter.drawLine(lineHEndPos, lineVEndPos, x1, y1); // 绘制箭头一半
painter.drawLine(lineHEndPos, lineVEndPos, x2, y2); // 绘制箭头另一半
}
// ---------------------------------------------------------------------------------------------------------------------------------------
void CalcVertexes(double startX, double startY, double endX, double endY, double& x1, double& y1, double& x2, double& y2)
{
/*
* @brief 求得箭头两点坐标
*/
double arrowLength = 10; // 箭头长度,一般固定
double arrowDegrees = 0.5; // 箭头角度,一般固定
// 求 y / x 的反正切值
double angle = atan2(endY - startY, endX - startX) + 3.1415926;
// 求得箭头点 1 的坐标
x1 = endX + arrowLength * cos(angle - arrowDegrees);
y1 = endY + arrowLength * sin(angle - arrowDegrees);
// 求得箭头点 2 的坐标
x2 = endX + arrowLength * cos(angle + arrowDegrees);
y2 = endY + arrowLength * sin(angle + arrowDegrees);
}