mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QMouseEvent> #include<Qpainter> #include<QDebug> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); protected: // 画图事件 void paintEvent(QPaintEvent *event); // 鼠标按下事件 void mousePressEvent(QMouseEvent *event); // 鼠标移动事件 void mouseMoveEvent(QMouseEvent *event); // 鼠标释放事件 void mouseReleaseEvent(QMouseEvent *event); // 窗口重置事件 virtual void resizeEvent(QResizeEvent *event) override; private: Ui::MainWindow *ui; QPixmap pix,temp; QPoint lastPoint; QPoint endPoint; qreal scale; bool flag; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "./ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QRect geometry = this->geometry(); int w = geometry.width(); int h = geometry.height(); pix = QPixmap(w,h); pix.fill(Qt::white); flag = false; } MainWindow::~MainWindow() { delete ui; } void MainWindow::paintEvent(QPaintEvent *){ int x,y,w,h; x = lastPoint.x(); y = lastPoint.y(); w = endPoint.x()-x; h = endPoint.y()-y; QPainter painter(this); if(flag){ temp = pix; QPainter ppainter(&temp); ppainter.drawRect(x,y,w,h); painter.drawPixmap(0,0,temp); }else{ QPainter ppainter(&pix); ppainter.drawRect(x,y,w,h); painter.drawPixmap(0,0,pix); } } void MainWindow::mousePressEvent(QMouseEvent *event){ if(event->button()==Qt::LeftButton){ lastPoint = event->pos(); flag = true; } } void MainWindow::mouseMoveEvent(QMouseEvent *event){ if(event->button()&Qt::LeftButton){ endPoint = event->pos(); update(); } } void MainWindow::mouseReleaseEvent(QMouseEvent *event){ if(event->button()==Qt::LeftButton){ endPoint = event->pos(); flag = false; update(); } } void MainWindow::resizeEvent(QResizeEvent *){ QRect geometry = this->geometry(); int w = geometry.width(); int h = geometry.height(); pix = QPixmap(w,h); pix.fill(Qt::white); }