之前写过用重写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;
}
源码连接:https://download.csdn.net/download/weixin_43935474/12511374