2022.9.2 作业

1、使用 Qt 实现画图板的基本功能

htTest.h

#ifndef HTTEST_H
#define HTTEST_H

#include <QWidget>
#include <QPixmap>
#include <QMouseEvent>
#include <QPainter>
#include <QPaintEvent>
#include <QPen>
#include <QColorDialog>

QT_BEGIN_NAMESPACE
namespace Ui { class htTest; }
QT_END_NAMESPACE

class htTest : public QWidget
{
    Q_OBJECT

public:
    htTest(QWidget *parent = nullptr);
    ~htTest();

    void mousePressEvent(QMouseEvent *e);
    void mouseMoveEvent(QMouseEvent *e);
    void paintEvent(QPaintEvent *e);
private slots:
    void on_colorBtn_clicked();

private:
    Ui::htTest *ui;
    QPixmap *mypix;
    QPoint startPoint;
    QColor pencolor;
};
#endif // HTTEST_H

htTest.cpp

#include "httest.h"
#include "ui_httest.h"

htTest::htTest(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::htTest)
{
    ui->setupUi(this);
    this->setFixedSize(1024,768);
    mypix=new QPixmap(this->size());
    mypix->fill();
    ui->colorBtn->setIcon(QIcon(":/icon/color.png"));
    pencolor=Qt::black;
}

htTest::~htTest()
{
    delete mypix;
    delete ui;
}

void htTest::mousePressEvent(QMouseEvent *e)
{
    if(e->buttons()==Qt::MidButton){
        delete this->mypix;
        mypix=new QPixmap(this->size());
        mypix->fill();
        this->update();
    }else{
        startPoint=e->pos();
    }
}

void htTest::mouseMoveEvent(QMouseEvent *e)
{
    if(e->buttons()==Qt::LeftButton){
        QPainter painter(this->mypix);
        QPen pen;
        pen.setColor(pencolor);
        pen.setWidth(5);
        painter.setPen(pen);
        painter.drawLine(startPoint,e->pos());
        startPoint=e->pos();
        this->update();
    }else if(e->buttons()==Qt::RightButton){
        QPainter painter(this->mypix);
        QPen pen;
        pen.setColor(Qt::white);
        pen.setWidth(30);
        painter.setPen(pen);
        painter.drawLine(startPoint,e->pos());
        startPoint=e->pos();
        this->update();
    }
}

void htTest::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,*mypix);
}

void htTest::on_colorBtn_clicked()
{
    QColor temp=pencolor;
    pencolor=QColorDialog::getColor(Qt::black,this,"画笔颜色");
    if(!pencolor.isValid()){
        pencolor=temp;
    }
}

运行界面:

 按住鼠标左键可以进行画线,按住鼠标右键可以实现“橡皮擦”功能,按下鼠标滚轮可以清空画图板。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值