最近在做在Label上显示图片并且通过鼠标点击画线,在网上查了很多零零散散的东西,收获也多
很多初学者更希望直接贴代码,这样可以模仿来写,我下面直接贴出我的项目中自己写的maLabel类(如果只是实现利用鼠标绘制,重写void paintEvent(QPaintEvent *event);void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e);即可,其他函数是我项目需求所以多写的,可以忽略)
申明myLabel类,继承QLabel,生成myLabel.h和myLabel.cpp文件
以下为我的代码,供参考。我只是实现了画一条直线,如果要画多条,可以用vector将之前若干条的信息干存下来,每次都绘制
myLabel.h
- #ifndef MYLABEL_H
- #define MYLABEL_H
- #include <QLabel>
- #include <QPoint>
- #include <QColor>
- #include <QPaintEvent>
- #include <QImage>
- #include <QPixmap>
-
- class myLabel : public QLabel
- {
- //Q_OBJECT
- public:
- myLabel();
- //~myLabel();
- //绘制线条
- virtual void paintEvent(QPaintEvent *event) override;
- //鼠标按下
- void mousePressEvent(QMouseEvent *e);
- //鼠标移动
- void mouseMoveEvent(QMouseEvent *e);
- //鼠标抬起
- void mouseReleaseEvent(QMouseEvent *e);
-
- //设置所画线条属性
- void setLineColor(const QColor lineColor);
- void setLineSize(const int lineSize);
- //得到画线的起点和终点
- QPoint getStartPoint();
- QPoint getEndPoint();
-
- void clear();
-
- private:
- QPoint lineStartPoint; //画线起点
- QPoint lineEndPoint; //画线终点
- QColor lineColor; //线条颜色
- int lineSize; //5种线型
- bool isPressed;
- };
-
- #endif // MYLABEL_H
myLabel.cpp
- #include "myLabel.h"
- #include <QPen>
- #include<QPainter>
-
- myLabel::myLabel()
- {
- this->lineStartPoint = QPoint(0,0);
- this->lineEndPoint = QPoint(0,0);
- this->lineColor = QColor(Qt::black);
- this->lineSize = 3;
- }
-
- //绘制线条
- void myLabel::paintEvent(QPaintEvent *event)
- {
- QLabel::paintEvent(event);//必须有,才能让背景图片显示出来
- QPainter painter(this);
- QPen pen;
- pen.setColor(lineColor);
- pen.setWidth(lineSize);
- painter.setPen(pen);
- painter.drawLine(lineStartPoint,lineEndPoint);
- }
-
- //鼠标按下
- void myLabel::mousePressEvent(QMouseEvent *e)
- {
- lineStartPoint = e->pos();
- lineEndPoint = e->pos();
- //在图片上绘制
- isPressed = true;
- }
-
- //鼠标移动
- void myLabel::mouseMoveEvent(QMouseEvent *e)
- {
- if(isPressed)
- {
- lineEndPoint=e->pos();
- update();
- }
- }
-
- //鼠标抬起
- void myLabel::mouseReleaseEvent(QMouseEvent *e)
- {
- isPressed=false;
- update();
- }
-
- void myLabel::setLineColor(const QColor lineColor)
- {
- this->lineColor = lineColor;
- }
-
- void myLabel::setLineSize(const int lineSize)
- {
- this->lineSize = lineSize;
- }
-
- QPoint myLabel::getStartPoint()
- {
- return lineStartPoint;
- }
-
- QPoint myLabel::getEndPoint()
- {
- return lineEndPoint;
- }
-
- void myLabel::clear()
- {
- lineStartPoint = QPoint(0,0);
- lineEndPoint = QPoint(0,0);
- update();
- }
