参考文章:https://blog.csdn.net/rl529014/article/details/51658350
一、双缓冲机制
二、效果图
三、示例代码
.h文件
#ifndef MYPIXMAP_H
#define MYPIXMAP_H
#include <QMouseEvent>
#include <QPaintEvent>
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class MyPixmap; }
QT_END_NAMESPACE
class MyPixmap : public QWidget
{
Q_OBJECT
public:
MyPixmap(QWidget *parent = nullptr);
~MyPixmap();
protected:
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void paintEvent(QPaintEvent *event);
public Q_SLOTS:
void onRed();
void onBlue();
void onGreen();
private:
Ui::MyPixmap *ui;
QPixmap *m_pPixmap;
QPoint m_point;
QColor m_color;
};
#endif // MYPIXMAP_H
在这里插入代码片
cpp文件
#include "MyPixmap.h"
#include "ui_MyPixmap.h"
#include <QPushButton>
#include <QPainter>
MyPixmap::MyPixmap(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MyPixmap)
{
ui->setupUi(this);
this->resize(800,600);
setAutoFillBackground(true);
//设置窗口背景颜色
setPalette(QPalette(Qt::white));
m_pPixmap = new QPixmap(this->width(),this->height());
//设置图片背景
m_pPixmap->fill(Qt::white);
connect(ui->red_Btn, &QPushButton::clicked, this, &MyPixmap::onRed);
connect(ui->green_Btn, &QPushButton::clicked, this, &MyPixmap::onGreen);
connect(ui->blue_Btn, &QPushButton::clicked, this, &MyPixmap::onBlue);
}
MyPixmap::~MyPixmap()
{
delete ui;
}
void MyPixmap::mouseMoveEvent(QMouseEvent *event)
{
Q_ASSERT(event);
QPainter painter;
QPen pen;
pen.setWidth(2);
pen.setColor(m_color);
painter.begin(m_pPixmap);
painter.setPen(pen);
painter.drawLine(m_point,event->pos());
painter.end();
m_point = event->pos();
update();
}
void MyPixmap::mousePressEvent(QMouseEvent *event)
{
Q_ASSERT(event);
m_point = event->pos();
}
void MyPixmap::paintEvent(QPaintEvent *event)
{
Q_ASSERT(event);
QPainter painter(this);
painter.drawPixmap(0,0, this->width(),this->height(),*m_pPixmap);
}
void MyPixmap::onRed()
{
m_color = QColor(Qt::red);
}
void MyPixmap::onBlue()
{
m_color = QColor(Qt::blue);
}
void MyPixmap::onGreen()
{
m_color = QColor(Qt::green);
}
``