创建项目名称:TestMouseEvent
在widget.cpp中添加代码

#include "widget.h"
#include "ui_widget.h"
#include <QEvent>
#include<QMouseEvent>
#include <QDebug>
#include <QPainter>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
   
    ui->setupUi(this);
}

Widget::~Widget()
{
   
    delete ui;
}

int i = 0, j = 0;
int jx1[1000], jy1[1000], jx2[1000], jy2[1000];
int xx1=0, yy1=0, xx2=0, yy2=0;
bool Widget::event(QEvent *ev)
{
   

    if ((ev->type() == QEvent::MouseButtonPress)&&(i%2==0))
    {
   
        i++;
        QMouseEvent *me1 = static_cast<QMouseEvent*> (ev);
        相对坐标
        //qDebug() << "MouseButtonPress " << me1->x() << ":" << me1->y();
        xx1 = me1->x();
        yy1 = me1->y();
        return QWidget::event(ev);
    }
    if ((ev->type() == QEvent::MouseButtonPress) && (i % 2 != 0))
    {
   
        i++;
        QMouseEvent *me2 = static_cast<QMouseEvent*> (ev);
        相对坐标
        //qDebug() << "MouseButtonPress " << me2->x() << ":" << me2->y();
        xx2 = me2->x();
        yy2 = me2->y();

    }
    if (i == 2)
    {
   
        i = 0;
        //qDebug() << xx1 << ":" << yy1 << "," << xx2 << ":" << yy2;


    }
    return QWidget::event(ev);
}
void Widget::paintEvent(QPaintEvent *ev)
{
   
    //设置绘制设备 (widget)
    QPainter p(this);
    p.begin(this);



    //绘制文本
    //p.drawText(100, 100, QStringLiteral("测试的显示文字"));

    //绘制线
    //设置画笔样式
    QPen pen;
    //实线
    pen.setStyle(Qt::SolidLine);
    //线粗
    pen.setWidth(7);
    //线刷子
    pen.setBrush(Qt::red);
    //结尾端样式
    pen.setCapStyle(Qt::RoundCap);

    //连接处样式
    pen.setJoinStyle(Qt::RoundJoin);

    p.setPen(pen);
    jx1[j] = xx1;
    jy1[j] = yy1;
    jx2[j] = xx2;
    jy2[j] = yy2;

int temp=0;
for(;temp<j;temp++)
{
   
    p.drawLine(QLine(jx1[temp],jy1[temp], jx2[temp], jy2[temp]));
}
    p.end();
    j++;

}

在widget.h中添加代码

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui {
    class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
   
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    bool event(QEvent *ev);
        void paintEvent(QPaintEvent *ev);
private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

ui设计(按钮绑定update()更新槽函数,其他颜色设计无影响)

运行结果

源代码:链接:https://pan.baidu.com/s/1iddQWPfhW-Mva_s6lpHUwQ
提取码:0816