Qt程序设计之画箭头的简单示例

Qt程序设计之QPainter类没有实现画箭头功能,比较遗憾。下面就自己实现一个,记录一下,方便以后查阅。

一、函数如下:

void drawArrow(QPointF p1, QPointF p2, QPainter &painter, int lineWidth = 3, int arrowLength = 20);

二、具体实现如下:

void MainWindow::drawArrow(QPointF p1, QPointF p2, QPainter &painter, int lineWidth, int arrowLength)
{
    painter.save();

    // 设置画笔
    QPen pen = painter.pen();
    pen.setWidth(lineWidth);
    pen.setJoinStyle(Qt::MiterJoin);
    painter.setPen(pen);

    // 设置画刷
    QBrush brush(painter.pen().color());
    painter.setBrush(brush);

    // 计算向量
    QLineF line(p1, p2);
    QLineF tmp = line.unitVector();
    tmp.setLength(line.length() - arrowLength);
    QLineF vector = line.unitVector();
    vector.setLength(arrowLength);
    vector.translate(tmp.dx(), tmp.dy());

    // 计算法向量
    QLineF n1, n2;
    n1 = vector.normalVector();
    n1.setLength(0.5 * arrowLength);
    n2 = n1.normalVector().normalVector();

    // 画多边形
    QVector<QPointF> vec = {vector.p2(), n1.p2(), n2.p2()};
    painter.drawPolygon(vec);
    painter.drawLine(line);

    painter.restore();
}

Leave a Reply

Your email address will not be published.