widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPoint> //点
#include <QMouseEvent> //鼠标事件
#include <QPaintEvent> //绘图事件class Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = 0);~Widget();void mousePressEvent(QMouseEvent *event); //鼠标按下事件void mouseMoveEvent(QMouseEvent *event); //鼠标移动事件void mouseReleaseEvent(QMouseEvent *event); //鼠标松开事件void paintEvent(QPaintEvent *event); //绘图事件private:bool toSave;QPoint pStart,pEnd; //起点和终点QPixmap *px; //缓冲的画布
};#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QPainter> //画家Widget::Widget(QWidget *parent): QWidget(parent)
{setFixedSize(800,600);px = new QPixmap(this->width(),this->height()); //与主窗口大小一致px->fill(); //不填充
}Widget::~Widget()
{}void Widget::mousePressEvent(QMouseEvent *event)
{pStart = event->pos(); //起点
}void Widget::mouseMoveEvent(QMouseEvent *event)
{pEnd = event->pos(); //终点toSave = false; //不保存//触发绘图事件this->update();
}void Widget::mouseReleaseEvent(QMouseEvent *event)
{pEnd = event->pos(); //终点toSave = true; //保存this->update(); //触发绘图事件
}void Widget::paintEvent(QPaintEvent *event)
{if(toSave) //区别移动还是松开{//当用户松开鼠标,将这根线画到pixmap//设定Pixmap作为画布QPainter p_pixmap(px); //两个画家在两个不同的画布上作画p_pixmap.drawLine(pStart,pEnd);}//让Widget成为画布QPainter p(this);//将之前保留的线画出来p.drawPixmap(0,0,*px);if(toSave == false){//只有鼠标移动的时候,我们才画这根临时的线p.drawLine(pStart,pEnd);}
}
结果