Qt中在QLabel上画点,重写QLabel类

Qt中在QLabel上画点,重写QLabel类

QT中label进行绘图

1.首先新建一个类,让这个类继承QLabel
2.在类中对鼠标点击事件及绘图事件进行重写
3.然后在UI框架下添加label控件,
4.右键label控件,添加重写的类,将其提升为刚刚写好的类

mylabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include 
#include 
#include 
#include 
#include 
#include 


class MyLabel : public QLabel

{

    Q_OBJECT

public:

    int labelWidth;
    int labelHeight;

    struct pointCoord{
        int x;
        int y;
    };

    std::vector coordList;

    bool paintEnable = true;

public:

    explicit MyLabel(QWidget *parent = 0);

    void enabelPaint(bool);

    void mousePressEvent(QMouseEvent *event);

    void paintEvent(QPaintEvent *event);

//    void mouseReleaseEvent(QMouseEvent *event);

//    void mouseMoveEvent(QMouseEvent *event);


signals:
    void updatePoint(int x, int y, int labelWidth, int labelHeight);

};


#endif // MYLABEL_H

mylabel.cpp

#include "mylabel.h"

#include 

#include 

#include 


MyLabel::MyLabel(QWidget *parent) : QLabel(parent)

{
;
}

void MyLabel::enabelPaint(bool enable){
    if (enable){
        paintEnable = true;
    } else {
        paintEnable = false;
    }

}

void MyLabel::mousePressEvent(QMouseEvent *event)

{
    if (paintEnable){
        int x = event->position().x();

        int y = event->position().y();

        pointCoord coord;
        coord.x = x;
        coord.y = y;

        coordList.push_back(coord);
        labelWidth = this->width();
        labelHeight = this->height();


        emit updatePoint(x, y, labelWidth, labelHeight);
        update();
    }

}


void MyLabel::paintEvent(QPaintEvent *event)

{

    QLabel::paintEvent(event);



    QPainter painter(this);

    QPen pen;       //设置画笔,颜色、宽度

    pen.setColor(Qt::red);

    pen.setWidth(5);

    painter.setPen(pen);


    for (auto coord:coordList){
        painter.drawPoint(coord.x, coord.y);
    }

}

你可能感兴趣的:(qt,开发语言)