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;
}
}
运行界面:
按住鼠标左键可以进行画线,按住鼠标右键可以实现“橡皮擦”功能,按下鼠标滚轮可以清空画图板。