重写QLabel实现图片显示框选截取保存

407 阅读2分钟

在这里插入图片描述
之前写过用重写QGraphicsItem的方式来实现图片显示,框选,保存的代码,这次通过重写QLabel的方式来实现。
主要重写QLabel的代码如下:
mylabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>

class myLabel:public QLabel
{
    Q_OBJECT
public:
    myLabel(QWidget *parent);
    ~myLabel();
    QPixmap m_loadPixmap;
    QPixmap m_capturePixmap;
    void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
private:
    bool m_isDown;
    QPoint m_start;
    QPoint m_stop;
    QRect getRect(const QPoint &beginPoint, const QPoint &endPoint);

Q_SIGNALS:
    void getPictureSig(QPixmap catureImage);
};

#endif // MYLABEL_H

mylabel.cpp

#include "mylabel.h"

myLabel::myLabel(QWidget *parent):QLabel(parent),m_start(QPoint(-1,-1)),m_stop(QPoint(-1,-1))
{

}

myLabel::~myLabel()
{

}

void myLabel::mousePressEvent(QMouseEvent *e)
{
    if(e->button() && Qt::LeftButton){
        m_isDown = true;
        m_start = e->pos();
        m_stop = e->pos();
    }
}

void myLabel::mouseMoveEvent(QMouseEvent *e)
{
    if(m_isDown){
        m_stop = e->pos();
    }
    update();
}

void myLabel::mouseReleaseEvent(QMouseEvent *e)
{
    if(e->button() && Qt::LeftButton){
        m_isDown = false;
        QRect selectedRect = getRect(m_start, m_stop);
        m_capturePixmap = m_loadPixmap.copy(selectedRect);
        emit getPictureSig(m_capturePixmap);//将框选的图片传给主界面
    }
}

void myLabel::paintEvent(QPaintEvent * event )
{
    QLabel::paintEvent(event);
    QPainter painter(this);
    painter.setPen(QPen(Qt::green,2));
    if(!m_isDown){
        return;
    }
    painter.drawRect(QRect(m_start,m_stop));
}

QRect myLabel::getRect(const QPoint &beginPoint, const QPoint &endPoint)
{
    int x, y, width, height;
    width = qAbs(beginPoint.x() - endPoint.x());
    height = qAbs(beginPoint.y() - endPoint.y());
    x = beginPoint.x() < endPoint.x() ? beginPoint.x() : endPoint.x();
    y = beginPoint.y() < endPoint.y() ? beginPoint.y() : endPoint.y();

    QRect selectedRect = QRect(x, y, width, height);
    // 避免宽或高为零时拷贝截图有误;
    if (selectedRect.width() == 0)
    {
        selectedRect.setWidth(1);
    }
    if (selectedRect.height() == 0)
    {
        selectedRect.setHeight(1);
    }
    return selectedRect;
}
#include "mainwindow.h"
```

```
#include "ui_mainwindow.h"
```

```
#pragma execution_character_set("utf-8")//让能够正常显示中文字符串
```

```
MainWindow::MainWindow(QWidget *parent) :
```

```
    QMainWindow(parent),
```

```
    ui(new Ui::MainWindow)
```

```
{
```

```
    ui->setupUi(this);
```

```
    label = new myLabel(this);
```

```
    //label->setGeometry(180,100,750,550);//设置label位置大小
```

```
    label->setText("Please Load Picture !");//显示文字
```

```
    label->setAlignment(Qt::AlignCenter);//文字水平垂直居中
```

```
    label->setStyleSheet("QLabel{background-color:rgb(200,200,200);}");//通过样式表设置背景色
```

```
    ui->verticalLayout->addWidget(label);
```

```
    QObject::connect(label,&myLabel::getPictureSig,this,&MainWindow::recvPicture);
```

```
}
```

```
```

```
MainWindow::~MainWindow()
```

```
{
```

```
    delete ui;
```

```
}
```

```
```

```
void MainWindow::on_pushButton_clicked()//打开文件
```

```
{
```

```
    QFileDialog *fileDlg = new QFileDialog(this);
```

```
    fileDlg->setWindowTitle("Choose Pictures");
```

```
    QStringList qstrFilters;
```

```
    qstrFilters<<"Image files(*.bmp *.jpg *.pbm *.pgm *.png *.ppm *.xbm *.xpm)";
```

```
    qstrFilters<<"Any files (*)";
```

```
    fileDlg->setNameFilters(qstrFilters);//设置文件过滤器
```

```
    fileDlg->setFileMode(QFileDialog::ExistingFile);//设置一次只能选中一个文件
```

```
    if(fileDlg->exec() == QDialog::Accepted)
```

```
    {
```

```
        QStringList lstName = fileDlg->selectedFiles();
```

```
        if(lstName.count()>0)//有选中的文件
```

```
        {
```

```
            ui->textEdit->setText(lstName.at(0));
```

```
            QImage img = QImage(lstName.at(0));
```

```
            QPixmap tempPix=QPixmap::fromImage(img);
```

```
            label->setPixmap(tempPix);
```

```
            label->resize(label->pixmap()->size());
```

```
//            QPixmap fitpixmap = QPixmap::fromImage(img).scaled(label->width(), label->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
```

```
//            label->setPixmap(fitpixmap);
```

```
            label->m_loadPixmap = tempPix;//QPixmap::grabWindow(label->winId()); // 抓取label窗口为复制区域
```

```
        }
```

```
    }
```

```
    fileDlg->close();
```

```
    delete fileDlg;
```

```
    fileDlg = nullptr;
```

```
}
```

```
```

```
void MainWindow::on_pushButton_2_clicked()//新增ROI区域
```

```
{
```

```
    lstPixmapROI.append(crtPixmapROI);
```

```
    for(int i = 0;i<lstPixmapROI.count();i++)
```

```
    {
```

```
        //lstPixmapROI[i].save("D://test.png");
```

```
        if(i ==0)
```

```
        {
```

```
            QPixmap fitpixmap = lstPixmapROI[i].scaled(ui->labelROI1->width(), ui->labelROI1->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  //按比例缩放
```

```
            ui->labelROI1->setPixmap(fitpixmap);
```

```
        }
```

```
        if(i ==1)
```

```
        {
```

```
            QPixmap fitpixmap = lstPixmapROI[i].scaled(ui->labelROI2->width(), ui->labelROI2->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  //按比例缩放
```

```
            ui->labelROI2->setPixmap(fitpixmap);
```

```
        }
```

```
        if(i ==2)
```

```
        {
```

```
            QPixmap fitpixmap = lstPixmapROI[i].scaled(ui->labelROI3->width(), ui->labelROI3->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
```

```
            ui->labelROI3->setPixmap(fitpixmap);
```

```
        }
```

```
        if(i ==3)
```

```
        {
```

```
            QPixmap fitpixmap = lstPixmapROI[i].scaled(ui->labelROI4->width(), ui->labelROI4->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
```

```
            ui->labelROI4->setPixmap(fitpixmap);
```

```
        }
```

```
        if(i ==4)
```

```
        {
```

```
            QPixmap fitpixmap = lstPixmapROI[i].scaled(ui->labelROI5->width(), ui->labelROI5->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
```

```
            ui->labelROI5->setPixmap(fitpixmap);
```

```
        }
```

```
    }
```

```
    label->update();
```

```
}
```

```
```

```
void MainWindow::recvPicture(QPixmap pix)
```

```
{
```

```
    crtPixmapROI = pix;
```

```
}
```

```
```

```
void MainWindow::on_pushButton_3_clicked()//批量保存ROI区域
```

```
{
```

```
    QString strFileName = QFileDialog::getSaveFileName(this,tr("Save Picture"),"","PNG(*.png);;JPG(*.jpg);;BMP(*.bmp)");
```

```
    for(int i = 0;i<lstPixmapROI.count();i++)
```

```
    {
```

```
        QString strNum = QString("%1").arg(i,4,10,QLatin1Char('0'));//0001保留4位数字,i之前自动补零
```

```
        int nIndex = strFileName.lastIndexOf('.');//寻找‘.’符号在字符串中的id
```

```
        QString strName0 = strFileName.left(nIndex);
```

```
        if(lstPixmapROI.count()>1)
```

```
        {
```

```
            strName0 += strNum;
```

```
        }
```

```
        nIndex++;
```

```
        int nLen = strFileName.length()-nIndex;
```

```
        QString strSuffix = strFileName.right(nLen);//截取‘.’符号后面的字符串,这是为了获取文件后缀名
```

```
        strName0 += "."+strSuffix;
```

```
        //QPixmap pix = QPixmap(m_strPathList[i]);
```

```
        lstPixmapROI[i].save(strName0,strSuffix.toUpper().toUtf8());
```

```
    }
```

```
}
```

```