Qt 实现涂鸦板一:简易涂鸦板

新建一个Qt项目,在 .h 文件中写入

#pragma once

#include <QtWidgets/QWidget>
#include "ui_xuexi.h"

#include "QMouseEvent"
#include "QKeyEvent"
#include "QPainter"

class xuexi : public QWidget
{
    Q_OBJECT

public:
    xuexi(QWidget *parent = Q_NULLPTR);

    void mousePressEvent(QMouseEvent*e);         // 按下
    void mouseMoveEvent(QMouseEvent*e);          // 移动
    void mouseReleaseRvent(QMouseEvent*e);       // 释放

    void paintEvent(QPaintEvent* );

private:
    Ui::xuexiClass ui;

    QPixmap pix;
    QPoint lastPoint;
    QPoint endPoint;
};

 

 

.cpp

#include "xuexi.h"

xuexi::xuexi(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);

    resize(600, 500);
    pix = QPixmap(200, 200);
    pix.fill(Qt::white);
}

void xuexi::mousePressEvent(QMouseEvent*e)
{
    if (e->button() == Qt::LeftButton)
    {
        lastPoint = e->pos();
    }
}

void xuexi::mouseMoveEvent(QMouseEvent*e)
{
    if (e->buttons() == Qt::LeftButton)
    {
        endPoint = e->pos();
        update();
    }
}

void xuexi::mouseReleaseRvent(QMouseEvent* e)
{
    if (e->button() == Qt::LeftButton)
    {
        endPoint = e->pos();
        update();
    }
}

void xuexi::paintEvent(QPaintEvent*)
{
    QPainter pp(&pix);
    pp.drawLine(lastPoint, endPoint);
    lastPoint = endPoint;

    QPainter painter(this);
    painter.drawPixmap(0, 0, pix);
}

 

编译后就是一个简易的涂鸦板

 

posted @ 2021-11-04 22:56  十一的杂文录  阅读(311)  评论(0编辑  收藏  举报