双缓冲绘图练习(20200217)

早过忘川 提交于 2020-02-16 16:50:58
#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

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!