//对别人的代码稍作修改,让自己更容易理解,绘制多边形的大致思路是一样的
DrawPolygon.h
#ifndef DRAWPOLYGON_H
#define DRAWPOLYGON_H
#include <QWidget>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPointF>
#include <QVector>
#include <QLineF>
#include <QPainter>
namespace Ui {
class DrawPolygon;
}
class DrawPolygon : public QWidget
{
Q_OBJECT
public:
explicit DrawPolygon(QWidget *parent = nullptr);
~DrawPolygon();
void drawPolygon(QPainter *painter); //绘制多边形
protected:
void paintEvent(QPaintEvent *); //绘制
void mousePressEvent(QMouseEvent *); //按下
void mouseMoveEvent(QMouseEvent *); //移动
void mouseReleaseEvent(QMouseEvent *); //松开
void mouseDoubleClickEvent(QMouseEvent *); //双击
private:
Ui::DrawPolygon *ui;
bool drawIsPolygon; //是否在绘制多边形
bool mouseIsMove; //是否在移动
bool mouseIsSingleClick; //是否是绘图之后的单击状态(为了区分单击和双击状态时的不同绘制)
QVector<QPointF> pointList; //存储所有绘制的点
QPointF movePoint; //移动状态下的点(还没有绘制完成)
};
#endif // DRAWPOLYGON_H
DrawPolygon.cpp
#include "drawpolygon.h"
#include "ui_drawpolygon.h"
DrawPolygon::DrawPolygon(QWidget *parent) :
QWidget(parent),
ui(new Ui::DrawPolygon)
{
ui->setupUi(this);
//设置背景颜色
this->setAutoFillBackground(true);
this->setBackgroundRole(QPalette::Base);
drawIsPolygon = false;
mouseIsMove = false;
mouseIsSingleClick = false;
//设置鼠标追踪
setMouseTracking(true);
}
DrawPolygon::~DrawPolygon()
{
delete ui;
}
void DrawPolygon::drawPolygon(QPainter *painter)
{
drawIsPolygon = true;
if(drawIsPolygon)
{
QVector<QLineF> lineList;
painter->setPen(QColor(250,200,0));
//存储前面的线段 线段的个数:pointList.size() - 1
for(int i = 0; i < pointList.size() - 1; i++ )
{
QLineF line(QPointF(pointList[i].x(), pointList[i].y()), QPointF(pointList[i + 1].x(), pointList[i + 1].y()));
lineList.push_back(line);
}
//存储还未生成的线段
if(mouseIsMove && pointList.size() > 0)
{
QLineF line(QPointF(pointList[pointList.size() - 1].x(), pointList[pointList.size() - 1].y()), movePoint);
lineList.push_back(line);
}
//绘制所有线段
painter->drawLines(lineList);
}
}
void DrawPolygon::paintEvent(QPaintEvent *)
{
QPainter painter(this);
//绘制多边形
drawPolygon(&painter);
}
void DrawPolygon::mousePressEvent(QMouseEvent *e)
{
if(drawIsPolygon)
{
//如果不是绘图后的单击状态
if(!mouseIsSingleClick)
{
//清空所有的点(当进行下一次绘制时不会有其他点的影响)
pointList.clear();
mouseIsSingleClick = true ;
}
}
}
void DrawPolygon::mouseMoveEvent(QMouseEvent *e)
{
//正在绘制多边形 并且 是绘图后的单击状态
if(drawIsPolygon && mouseIsSingleClick)
{
//移动的点(用来动态绘制 鼠标移动连接的线段)
movePoint = e->pos();
mouseIsMove = true;
this->update();
}
}
void DrawPolygon::mouseReleaseEvent(QMouseEvent *e)
{
//正在绘制多边形 并且 是绘图后的单击状态
if(drawIsPolygon && mouseIsSingleClick)
{
//将点保存到容器中(鼠标松开之后才能确定生成的点)
pointList.push_back(e->pos());
mouseIsMove = false;
this->update();
}
}
void DrawPolygon::mouseDoubleClickEvent(QMouseEvent *e)
{
if(drawIsPolygon)
{
mouseIsSingleClick = false;
//将第一个点传给容器,为了让最后一个点与第一个点在双击之后进行相连
pointList.push_back(pointList[0]);
this->update();
}
}
运行结果:
参考博客:
https://blog.csdn.net/charlee44/article/details/104696765