Qt 绘制路径并显示长度:DrawPath 类详解
//drawpath.cpp
#include "drawpath.h"
#include
#include <math.h> #include <stdio.h>
// 构造函数 DrawPath::DrawPath(QWidget *parent) : QWidget(parent) { isForDrawLine=false; // 初始化为不绘制路径
pathLengthLabel=new QLabel(this); // 创建路径长度标签
clearpath=false; // 初始化为不清除路径
}
// 绘图事件函数 void DrawPath::paintEvent (QPaintEvent *e) { QPainter painter(this); // 创建画家对象
QPixmap background("image/beijing2.png"); // 创建背景图像对象
painter.drawPixmap (0,0,background.width (),background.height (),background); // 绘制背景图像
QWidget::paintEvent(e); // 调用父类的绘图事件函数
drawPath(&painter); // 绘制路径
}
// 设置要绘制的路径
void DrawPath::setDrawLine (QVector
this->repaint (); // 重绘窗口界面
}
// 绘制路径 void DrawPath::drawPath (QPainter *painter) { if(isForDrawLine) // 如果要绘制路径 { QPen pen(QColor(223, 0, 0, 255)); // 创建画笔对象,设置颜色为红色,透明度为255
pen.setWidth (4); // 设置画笔宽度为4
pen.setJoinStyle (Qt::RoundJoin); // 设置画笔线段连接处的形状为圆形
pen.setCapStyle (Qt::RoundCap); // 设置画笔线段两端的形状为圆形
painter->setPen(pen); // 将画笔设置为当前画家的画笔
QPainterPath path; // 创建绘制路径对象
path.moveTo (pathPoint[pathPoint.size ()-1]); // 将路径起点设置为路径点的最后一个坐标值
for(int i=pathPoint.size ()-2;i>=0;i--) // 从路径点倒数第二个点开始,依次连接路径点
{
path.lineTo (pathPoint[i]);
}
painter->drawPath (path); // 绘制路径
initPathLength(); // 初始化路径长度
}
}
// 初始化路径长度 void DrawPath::initPathLength () { // 设置路径长度标签的样式 pathLengthLabel->setStyleSheet ("background-color: qlineargradient(spread:pad, x1:0.0743636, y1:0.068, x2:0.965909, y2:0.988, stop:0 rgba(223, 191, 255, 255), stop:1 rgba(255, 255, 255, 255));");
// 设置路径长度标签的文本内容
pathLengthLabel->setText (QString(QString::fromLocal8Bit ("长度:")+QString::number (pathLength))+"m");
// 将路径长度标签移动到路径的起点处
pathLengthLabel->move (pathPoint[0]);
// 调整路径长度标签的大小,使其自适应文本内容的大小
pathLengthLabel->resize (pathLengthLabel->sizeHint ());
pathLengthLabel->show (); // 显示路径长度标签
}
// 清除路径 void DrawPath::clearPathLine (bool yes) { if(yes) // 如果要清除路径 { isForDrawLine=false; // 将是否绘制路径的标志设置为false
pathLengthLabel->hide (); // 隐藏路径长度标签
this->update (); // 更新窗口界面
}
}
// 鼠标按下事件函数 void DrawPath::mousePressEvent ( QMouseEvent * event ) { if(event->button ()==Qt::RightButton) // 如果按下的是右键 { clearPathLine(true); // 清除路径 } }
// 设置路径长度 void DrawPath::setPathLength (double pathLength) { this->pathLength=pathLength; // 将路径长度存储起来 }
原文地址: https://www.cveoy.top/t/topic/offy 著作权归作者所有。请勿转载和采集!