参考:https://www.cnblogs.com/lsgxeva/p/7821550.html
效果图:
void BrokenLine::paintEvent(QPaintEvent *event)
{
// 折线上的点
static QList<QPointF> points = QList<QPointF>() << QPointF(10, 40) << QPointF(100, 100) << QPointF(200, 100)
<< QPointF(300, 100) << QPointF(330, 80) << QPointF(350, 70);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 2));
QPainterPath path(points[0]);
for (int i = 1; i < points.size(); ++i)
{
path.lineTo(points[i]);
}
// 绘制 path
painter.drawPath(path);
// 绘制折线上的标记点
painter.setBrush(Qt::gray);
int ellipse_size = 4;
for (int i = 0; i < points.size(); ++i) {
painter.drawEllipse(points[i], ellipse_size, ellipse_size);
QString text = QString::number(points[i].y());
QFontMetrics fm = painter.fontMetrics();
int height_font = fm.height();
int width_text = fm.width(text);
QPointF textPos(points[i].x()-(width_text/2), points[i].y()-(ellipse_size/2)-(height_font/2));
painter.drawText(textPos, text);
}
return QWidget::paintEvent(event);
}