绘制动态矩形
drawRects.h
#ifndef DRAWRECTS_H
#define DRAWRECTS_H
#include <QWidget>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QPainter>
#include <QVector>
#include <QRect>
#include <QPoint>
namespace Ui {
class DrawRects;
}
class DrawRects : public QWidget
{
Q_OBJECT
public:
explicit DrawRects(QWidget *parent = nullptr);
~DrawRects();
void drawRects(QPainter *painter); //绘制多个矩形
protected:
void paintEvent(QPaintEvent *); //绘制
void mousePressEvent(QMouseEvent *); //按下
void mouseMoveEvent(QMouseEvent *); //移动
void mouseReleaseEvent(QMouseEvent *); //松开
private:
Ui::DrawRects *ui;
bool drawIsRects; //是否在绘制多个矩形
bool mouseIsMove; //是否在移动
bool mouseIsClickKeep; //是否鼠标保持移动(鼠标没松开)
bool drawIsFinshed; //绘图是否完成
QVector<QPoint> rectPoint; //存储绘制矩形的点
QPoint movePoint; //存储移动的点(鼠标点击未松开)
};
#endif // DRAWRECTS_H
drawRects.cpp
#include "drawrects.h"
#include "ui_drawrects.h"
DrawRects::DrawRects(QWidget *parent) :
QWidget(parent),
ui(new Ui::DrawRects)
{
ui->setupUi(this);
drawIsRects = false;
mouseIsMove = false;
mouseIsClickKeep = false;
drawIsFinshed = false;
}
DrawRects::~DrawRects()
{
delete ui;
}
void DrawRects::drawRects(QPainter *painter)
{
drawIsRects = true;
if(drawIsRects)
{
//记录矩形的个数
int rectCount = 0;
if(rectPoint.size() % 2 == 0 )
{
rectCount = rectPoint.size() / 2;
}
else
{
rectCount = (rectPoint.size() - 1) / 2;
}
//绘制未完成的(移动状态)矩形
if(mouseIsMove && mouseIsClickKeep)
{
int width = movePoint.x() - rectPoint[rectCount * 2].x();
int height = movePoint.y() - rectPoint[rectCount * 2].y();
painter->drawRect(QRect(rectPoint[rectCount * 2].x(), rectPoint[rectCount * 2].y(), width, height));
}
//绘制完成的矩形
for(int i = 0; i < rectCount; i++)
{
int width = rectPoint[i * 2 + 1].x() - rectPoint[i * 2].x();
int height = rectPoint[i * 2 + 1].y() - rectPoint[i * 2].y();
painter->drawRect(QRect(rectPoint[i * 2].x(), rectPoint[i * 2].y(), width, height));
}
}
}
void DrawRects::paintEvent(QPaintEvent *)
{
QPainter painter(this);
drawRects(&painter);
}
void DrawRects::mousePressEvent(QMouseEvent *e)
{
if(drawIsRects)
{
//鼠标是否是保持按下不变的状态
if(!mouseIsClickKeep)
{
mouseIsClickKeep = true;
//将点击的点存放在容器中
rectPoint.push_back(e->pos());
drawIsFinshed = false;
this->update();
}
}
}
void DrawRects::mouseMoveEvent(QMouseEvent *e)
{
if(drawIsRects && mouseIsClickKeep)
{
//记录移动状态时候的点
movePoint = e->pos();
mouseIsMove = true;
drawIsFinshed = false;
this->update();
}
}
void DrawRects::mouseReleaseEvent(QMouseEvent *e)
{
if(drawIsRects)
{
mouseIsClickKeep = false;
mouseIsMove = false;
drawIsFinshed = true;
rectPoint.push_back(e->pos());
this->update();
}
}
运行结果: