[Qt]基于QGraphicsView的图像显示控件,支持放大、缩小、鼠标拖动等操作
前言
这是一个Qt平台的基于QGraphicsView类的图像显示控件,支持输入QPixmap、QImage、opencv的从cv::Mat类。
实现平台:Windows 10 x64 + Qt 6.2.3 + MSVC 2019 + opencv 4.5
先来看演示视频
控件类实现
ImageViewer.h文件
#ifndef IMAGEVIEWER_H
#define IMAGEVIEWER_H
#include <QObject>
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QMouseEvent>
#include <QImage>
#include <QWheelEvent>
#include <QGraphicsScene>
#include "opencv2/opencv.hpp"
class ImageViewer : public QGraphicsView
{
Q_OBJECT
public:
explicit ImageViewer(QWidget *parent = nullptr);
signals:
public:
void setQImage(QImage);
void setMatImage(cv::Mat );
void setPixmap(QPixmap);
void resetImage();
QImage getQImage();
cv::Mat getMatImage();
QPixmap getPixmap();
protected:
virtual void wheelEvent(QWheelEvent *event) override;
virtual void keyPressEvent(QKeyEvent *event) override;
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *event) override;
virtual void mouseReleaseEvent(QMouseEvent *event) override;
void zoom(QPoint factor);
void togglePan(bool pan, const QPoint &startPos = QPoint());
void pan(const QPoint &panTo);
void initShow();
private:
QPixmap m_image;
bool m_isPan;
QPoint m_prevPan;
QGraphicsScene *scene;
};
#endif // IMAGEVIEWER_H
ImageViewer.cpp 文件
#include "imageviewer.h"
#include <QScrollBar>
ImageViewer::ImageViewer(QWidget *parent)
: QGraphicsView{parent},
m_isPan(false),
m_prevPan(0,0),
scene(nullptr)
{
scene = new QGraphicsScene(this);
this->setScene(scene);
setDragMode(QGraphicsView::DragMode::NoDrag);
setInteractive(false);
setEnabled(false);
}
QImage cvMatToQImage(cv::Mat &src)
{
if(src.channels() == 1) { // if grayscale image
return QImage((uchar*)src.data, src.cols, src.rows, static_cast<int>(src.step), QImage::Format_Grayscale8).copy();
}
if(src.channels() == 3) { // if 3 channel color image
cv::Mat rgbMat;
cv::cvtColor(src, rgbMat, cv::COLOR_BGR2RGB); // invert BGR to RGB
return QImage((uchar*)rgbMat.data, src.cols, src.rows, static_cast<int>(src.step), QImage::Format_RGB888).copy();
}
return QImage();
}
//将QImage转化为Mat
cv::Mat qImageToCvMat( const QImage &inImage)
{
switch (inImage.format())
{
case QImage::Format_RGB32:
case QImage::Format_RGB888:
{
QImage swapped = inImage;
if ( inImage.format() == QImage::Format_RGB32 )
{
swapped = swapped.convertToFormat( QImage::Format_RGB888 );
}
cv::Mat matImg = cv::Mat(swapped.height(), swapped.width(),
CV_8UC3,
const_cast<uchar*>(swapped.bits()),
static_cast<size_t>(swapped.bytesPerLine())
);
cv::cvtColor(matImg,matImg,cv::COLOR_RGB2BGR);
return matImg.clone();
}
case QImage::Format_Indexed8:
{
cv::Mat mat( inImage.height(), inImage.width(),
CV_8UC1,
const_cast<uchar*>(inImage.bits()),
static_cast<size_t>(inImage.bytesPerLine())
);
return mat.clone();
}
default:
break;
}
return cv::Mat();
}
void ImageViewer::setQImage(QImage image)
{ if(image.isNull())
return;
m_image = QPixmap::fromImage(image);
initShow();
}
void ImageViewer::setMatImage(cv::Mat src)
{
if(src.empty())
return;
m_image = QPixmap::fromImage(cvMatToQImage(src));
initShow();
}
void ImageViewer::setPixmap(QPixmap pixmap)
{
m_image = pixmap.copy();
initShow();
}
void ImageViewer::resetImage()
{
if(m_image.isNull())
return;
scene->clear();
setEnabled(false);
}
QImage ImageViewer::getQImage()
{
return m_image.toImage();
}
cv::Mat ImageViewer::getMatImage()
{
return qImageToCvMat(m_image.toImage());
}
QPixmap ImageViewer::getPixmap()
{
return m_image;
}
void ImageViewer::initShow()
{
setEnabled(true);
setMouseTracking(true);
scene->clear();
scene->addPixmap(m_image);
scene->update();
this->resetTransform();
this->setSceneRect(m_image.rect());
this->fitInView(QRect(0, 0, m_image.width(), m_image.height()), Qt::KeepAspectRatio);
}
void ImageViewer::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
togglePan(true, event->pos());
event->accept();
return;
}
event->ignore();
}
void ImageViewer::mouseMoveEvent(QMouseEvent *event)
{
if(m_isPan) {
pan(event->pos());
event->accept();
return;
}
event->ignore();
}
void ImageViewer::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
togglePan(false);
event->accept();
return;
}
event->ignore();
}
void ImageViewer::zoom(QPoint factor)
{
QRectF FOV = this->mapToScene(this->rect()).boundingRect();
QRectF FOVImage = QRectF(FOV.left(), FOV.top(), FOV.width(), FOV.height());
float scaleX = static_cast<float>(m_image.width()) / FOVImage.width();
float scaleY = static_cast<float>(m_image.height()) / FOVImage.height();
float minScale = scaleX > scaleY ? scaleY : scaleX;
float maxScale = scaleX > scaleY ? scaleX : scaleY;
if ((factor.y() > 0 && minScale > 100) || (factor.y() < 0 && maxScale < 1 )) {
return;
}
if(factor.y()>0)
scale(1.2, 1.2);
else
scale(0.8, 0.8);
}
void ImageViewer::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_O) {
this->resetTransform();
this->setSceneRect(m_image.rect());
this->fitInView(QRect(0, 0, m_image.width(), m_image.height()), Qt::KeepAspectRatio);
}
}
void ImageViewer::pan(const QPoint &panTo)
{
auto hBar = horizontalScrollBar();
auto vBar = verticalScrollBar();
auto delta = panTo - m_prevPan;
m_prevPan = panTo;
hBar->setValue(hBar->value() - delta.x());
vBar->setValue(vBar->value() - delta.y());
}
void ImageViewer::wheelEvent(QWheelEvent *event)
{
if(m_image.isNull())
return;
QPoint numDegrees = event->angleDelta() / 8;
if (!numDegrees.isNull()) {
QPoint numSteps = numDegrees / 15;
zoom(numSteps);
}
event->accept();
}
void ImageViewer::togglePan(bool pan, const QPoint &startPos)
{
if(pan){
if(m_isPan) {
return;
}
m_isPan = true;
m_prevPan = startPos;
setCursor(Qt::ClosedHandCursor);
} else {
if(!m_isPan) {
return;
}
m_isPan = false;
m_prevPan = QPoint(0,0);
setCursor(Qt::ArrowCursor);
}
}
控件类的使用
具体使用代码如下
1、初始化类对象,并加入界面布局中
//初始化图片浏览控件,并添加到布局
m_view = new ImageViewer(this);
//在界面的一个布局中加入控件
ui->horizontalLayout_3->addWidget(m_view);
2、打开图像,并加载到控件中
QString filename = getFilePath(QDir::currentPath(),this);
qDebug() << filename;
if(filename == "")
return;
//读取为QPixmap
QPixmap mapImg(filename);
m_view->setPixmap(mapImg);
//读取为QImage
// QImage img(filename);
// m_view->setQImage(img);
//读取为cv::Mat
// cv::Mat matImg = cv::imread(filename.toLocal8Bit().data(),cv::IMREAD_UNCHANGED);
// m_view->setMatImage(matImg);
3、从控件中卸载图片
m_view->resetImage();
如果还是看不懂、建议直接下载源代码
源码链接:https://download.csdn.net/download/xiaohuihuihuige/87239431
百度云:
链接:https://pan.baidu.com/s/1W-KUlIKUFAktUKFin63N0g
提取码:4g8a