Qt Qlable 画roi区域

Qt Qlable 画roi区域_第1张图片
MyLabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include 
#include 
#include 

class MyLabel : public QLabel
{
public:
    MyLabel(QWidget* parent = nullptr);

    // QWidget interface
protected:
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void paintEvent(QPaintEvent *event);
private:
    QVector points;
    QPoint mousePoint;
    bool endPainter{false};
};

#endif // MYLABEL_H

MyLabel.cpp

#include "MyLabel.h"

#include 
#include 
#include 
#include 
#include 

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

    setMouseTracking(true);
}

void MyLabel::mousePressEvent(QMouseEvent *event)
{
    if(!endPainter){
        if(points.size())
            points.push_back(event->pos());
        points.push_back(event->pos());
    }
    update();
}

void MyLabel::mouseMoveEvent(QMouseEvent *event)
{
    mousePoint= event->pos();
    update();
}
double calculateDistance(QPoint &p1, QPoint &p2)
{
    return sqrt(pow(p1.x() - p2.x(), 2) +
                pow(p1.y() - p2.y(), 2));
}


void MyLabel::paintEvent(QPaintEvent *event)
{

    QPainter painter(this);
    QPen pen;
    pen.setWidth(3);
    pen.setColor(Qt::red);
    painter.setPen(pen);
    if(points.size() ){
        painter.drawLines(points);
        if(!endPainter){
            painter.drawLine(points.last(),mousePoint);
            if(calculateDistance(points.first(),mousePoint) < 5 && points.size() >=5){
                points.push_back(points.first());
                endPainter= true;
            }
        }
    }
    QLabel::paintEvent(event);
}

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