#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_canvasPix = QPixmap(this->width(),this->height());
m_canvasPix.fill(Qt::white);
m_bIsDrawing = false;
}
Widget::~Widget()
{
}
void Widget::paintEvent(QPaintEvent *event)
{
int x,y,w,h;
x = m_lastPt.x();
y = m_lastPt.y();
w = m_endPt.x() - x;
h = m_endPt.y() - y;
QPainter painter(this);
//! 如果正在绘图,就在辅助画布上绘制
if(m_bIsDrawing)
{
//! 将以前pix中的内容复制到tempPix中,保证以前的内容不消失
m_tmpCanvasPix = m_canvasPix;
QPainter pp(&m_tmpCanvasPix);
pp.drawRect(x,y,w,h);
painter.drawPixmap(0, 0, m_tmpCanvasPix);
} else {
QPainter pp(&m_canvasPix);
pp.drawRect(x,y,w,h);
painter.drawPixmap(0,0,m_canvasPix);
}
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton){
m_lastPt = event->pos();
m_bIsDrawing = true; //正在绘图
}
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton){
m_endPt = event->pos();
m_bIsDrawing = false;
update();
}
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() == Qt::LeftButton){
m_endPt = event->pos();
update();
}
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <qlayout.h>
#include <QPainter>
#include <QMouseEvent>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
QPixmap m_canvasPix;
QPoint m_lastPt;
QPoint m_endPt;
QPixmap m_tmpCanvasPix; //! 辅助画布
bool m_bIsDrawing; //! 标志是否正在绘图
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
};
#endif // WIDGET_H
来源:CSDN
作者:浩瀚之水_csdn
链接:https://blog.csdn.net/a8039974/article/details/104340559