RectView.h
#ifndef RECTVIEW_H
#define RECTVIEW_H
#include <QObject>
#include <QGraphicsView>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QKeyEvent>
#include <QPainter>
#include <QPixmap>
#include <QDebug>
class RectView : public QGraphicsView
{
Q_OBJECT
public:
RectView(QWidget *parent);
~RectView();
// QWidget interface
protected:
void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE;
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE;
private:
QPixmap pix;
QPoint lasetPoint;
QPoint endPoint;
QPixmap tempPix;
bool isDrawing;
bool isDoubleClick;
};
#endif // RECTVIEW_H
RectView.cpp
#include "rectview.h"
RectView::RectView(QWidget *parent) : QGraphicsView(parent)
{
isDrawing = false;
isDoubleClick = false;
}
RectView::~RectView()
{
}
void RectView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
lasetPoint = event->pos();
isDrawing = true;
isDoubleClick = false;
}
QGraphicsView::mousePressEvent(event);
}
void RectView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if (!isDoubleClick) {
endPoint = event->pos();
isDrawing = false;
this->viewport()->update();
}
}
QGraphicsView::mouseReleaseEvent(event);
}
void RectView::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
isDoubleClick = true;
}
QGraphicsView::mouseDoubleClickEvent(event);
}
void RectView::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
if (!isDoubleClick) {
endPoint = event->pos();
this->viewport()->update();
}
}
QGraphicsView::mouseMoveEvent(event);
}
void RectView::keyPressEvent(QKeyEvent *event)
{
QGraphicsView::keyPressEvent(event);
}
/**
* @brief RectView::paintEvent
* 双缓冲绘图,原理是在拖动过程中先把原来的图形复制到tempPix里面并在tempPix里面画,
* 我们此时看到的就是在tempPix里的图形。只在鼠标释放的时候才在pix绘一次。
*/
void RectView::paintEvent(QPaintEvent *event)
{
QPainter painter(this->viewport());
if (isDrawing)
{
tempPix = pix;
QPainter pp(&tempPix);
pp.drawLine(lasetPoint, endPoint);
painter.drawPixmap(0, 0, tempPix);
}
else
{
QPainter pp(&pix);
pp.drawLine(lasetPoint, endPoint);
painter.drawPixmap(0, 0, pix);
}
QGraphicsView::paintEvent(event);
}
//这里才是真正读取控件宽高的地方
void RectView::resizeEvent(QResizeEvent *event)
{
pix = QPixmap(width(), height());
pix.fill(Qt::white);
}