Qt 使用QPainter实现双缓冲画图板

参考文章: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);
}
``
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值