QGraphicsView实现图片放大、缩小、鼠标拖动、以鼠标点放大缩小

1. 工程配置文件 pro

cpp 复制代码
1 QT       += core gui
 2 
 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 4 
 5 CONFIG += c++11
 6 
 7 # The following define makes your compiler emit warnings if you use
 8 # any Qt feature that has been marked deprecated (the exact warnings
 9 # depend on your compiler). Please consult the documentation of the
10 # deprecated API in order to know how to port your code away from it.
11 DEFINES += QT_DEPRECATED_WARNINGS
12 
13 # You can also make your code fail to compile if it uses deprecated APIs.
14 # In order to do so, uncomment the following line.
15 # You can also select to disable deprecated APIs only up to a certain version of Qt.
16 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
17 
18 SOURCES += \
19     ImageWidget.cpp \
20     main.cpp \
21     mainwindow.cpp
22 
23 HEADERS += \
24     ImageWidget.h \
25     mainwindow.h
26 
27 FORMS += \
28     mainwindow.ui
29 
30 # Default rules for deployment.
31 qnx: target.path = /tmp/$${TARGET}/bin
32 else: unix:!android: target.path = /opt/$${TARGET}/bin
33 !isEmpty(target.path): INSTALLS += target
34 
35 RESOURCES += \
36

2. main.cpp

cpp 复制代码
1 #include "mainwindow.h"
 2 
 3 #include <QApplication>
 4 
 5 int main(int argc, char *argv[])
 6 {
 7     QApplication a(argc, argv);
 8     MainWindow w;
 9     w.show();
10     return a.exec();
11

3. mainwindow.h

cpp 复制代码
1 #ifndef MAINWINDOW_H
 2 #define MAINWINDOW_H
 3 
 4 #include <QMainWindow>
 5 #include <QPixmap>
 6 #include <QGraphicsScene>
 7 #include <QGraphicsPixmapItem>
 8 #include <QWheelEvent>
 9 
10 #include "ImageWidget.h"
11 
12 QT_BEGIN_NAMESPACE
13 namespace Ui { class MainWindow; }
14 QT_END_NAMESPACE
15 
16 class MainWindow : public QMainWindow
17 {
18     Q_OBJECT
19 
20 public:
21     MainWindow(QWidget *parent = nullptr);
22     ~MainWindow();
23 
24     void recvShowPicSignal(QImage image);//接收并显示图片的函数
25 private:
26     Ui::MainWindow *ui;
27     ImageWidget *m_Image;
28 };
29 #endif // MAINWINDOW_H

4. mainwindow.cpp

cpp 复制代码
1 #include "mainwindow.h"
 2 #include "ui_mainwindow.h"
 3 
 4 MainWindow::MainWindow(QWidget *parent)
 5     : QMainWindow(parent)
 6     , ui(new Ui::MainWindow)
 7 {
 8     ui->setupUi(this);
 9 
10     setWindowTitle(QStringLiteral("QtQGraphicsView实现图片放大、缩小、鼠标拖动、以鼠标点放大缩小"));
11 
12     QPixmap *backgroundPixmap = new QPixmap(":/new/prefix1/QtImage.png");
13     QImage sizedImage = QImage(backgroundPixmap->toImage());
14     recvShowPicSignal(sizedImage);
15 }
16 
17 MainWindow::~MainWindow()
18 {
19     delete ui;
20 }
21 
22 void MainWindow::recvShowPicSignal(QImage image)
23 {
24     ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
25     ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
26 
27     QPixmap ConvertPixmap = QPixmap::fromImage(image);//The QPixmap class is an off-screen image representation that can be used as a paint device
28     QGraphicsScene  *qgraphicsScene = new QGraphicsScene;//要用QGraphicsView就必须要有QGraphicsScene搭配着用
29     m_Image = new ImageWidget(&ConvertPixmap);//实例化类ImageWidget的对象m_Image,该类继承自QGraphicsItem,是自己写的类
30     int nwith = ui->graphicsView->width();//获取界面控件Graphics View的宽度
31     int nheight = ui->graphicsView->height();//获取界面控件Graphics View的高度
32     m_Image->setQGraphicsViewWH(nwith,nheight);//将界面控件Graphics View的width和height传进类m_Image中
33     qgraphicsScene->addItem(m_Image);//将QGraphicsItem类对象放进QGraphicsScene中
34     ui->graphicsView->setSceneRect(QRectF(-(nwith/2),-(nheight/2),nwith,nheight));//使视窗的大小固定在原始大小,不会随图片的放大而放大(默认状态下图片放大的时候视窗两边会自动出现滚动条,并且视窗内的视野会变大),防止图片放大后重新缩小的时候视窗太大而不方便观察图片
35     ui->graphicsView->setScene(qgraphicsScene);//Sets the current scene to scene. If scene is already being viewed, this function does nothing.
36     ui->graphicsView->setFocus();//将界面的焦点设置到当前Graphics View控件
37

5. mainwindow.ui

cpp 复制代码
1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ui version="4.0">
 3  <class>MainWindow</class>
 4  <widget class="QMainWindow" name="MainWindow">
 5   <property name="geometry">
 6    <rect>
 7     <x>0</x>
 8     <y>0</y>
 9     <width>600</width>
10     <height>400</height>
11    </rect>
12   </property>
13   <property name="windowTitle">
14    <string>MainWindow</string>
15   </property>
16   <widget class="QWidget" name="centralwidget">
17    <widget class="QGraphicsView" name="graphicsView">
18     <property name="geometry">
19      <rect>
20       <x>0</x>
21       <y>0</y>
22       <width>600</width>
23       <height>400</height>
24      </rect>
25     </property>
26    </widget>
27   </widget>
28  </widget>
29  <resources/>
30  <connections/>
31

6. ImageWidget.h

cpp 复制代码
1 #ifndef IMAGEWIDGET_H
 2 #define IMAGEWIDGET_H
 3 
 4 #include <QWidget>
 5 #include <QtGui>
 6 #include <QPixmap>
 7 #include <QPainter>
 8 #include <QRectF>
 9 #include <QMouseEvent>
10 #include <QPointF>
11 #include <QDragEnterEvent>
12 #include <QGraphicsSceneWheelEvent>
13 #include <QGraphicsItem>
14 
15 enum Enum_ZoomState{
16     NO_STATE,
17     RESET,
18     ZOOM_IN,
19     ZOOM_OUT
20 };
21 // class ImageWidget :public QObject, QGraphicsItem
22 class ImageWidget :public QGraphicsItem
23 {
24     //Q_OBJECT
25 public:
26     ImageWidget(QPixmap *pixmap);
27     QRectF  boundingRect() const;
28     void    paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
29     void    wheelEvent(QGraphicsSceneWheelEvent *event);
30     void    ResetItemPos();
31     void    mousePressEvent(QGraphicsSceneMouseEvent *event);
32     void    mouseMoveEvent(QGraphicsSceneMouseEvent *event);
33     void    mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
34     qreal   getScaleValue() const;
35     void    setQGraphicsViewWH(int nwidth,int nheight);
36 private:
37     qreal       m_scaleValue;
38     qreal       m_scaleDafault;
39     QPixmap     m_pix;
40     int         m_zoomState;
41     bool        m_isMove;
42     QPointF     m_startPos;
43 };
44 #endif // IMAGEWIDGET_H

7. ImageWidget.cpp

cpp 复制代码
1 #include "ImageWidget.h"
  2 
  3 #include <QDebug>
  4 #include <QGraphicsSceneMouseEvent>
  5 #include <QPointF>
  6 #include <QGraphicsSceneDragDropEvent>
  7 #include <QDrag>
  8 #include <math.h>
  9 
 10 ImageWidget::ImageWidget(QPixmap *pixmap)
 11 {
 12     m_pix = *pixmap;
 13     setAcceptDrops(true);//If enabled is true, this item will accept hover events; otherwise, it will ignore them. By default, items do not accept hover events.
 14     m_scaleValue = 0;
 15     m_scaleDafault = 0;
 16     m_isMove = false;
 17 }
 18 
 19 QRectF ImageWidget::boundingRect() const
 20 {
 21     return QRectF(-m_pix.width() / 2, -m_pix.height() / 2,
 22                   m_pix.width(), m_pix.height());
 23 }
 24 
 25 void ImageWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
 26                     QWidget *)
 27 {
 28     painter->drawPixmap(-m_pix.width() / 2, -m_pix.height() / 2, m_pix);
 29 }
 30 
 31 void ImageWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
 32 {
 33     if(event->button()== Qt::LeftButton)
 34     {
 35         m_startPos = event->pos();//鼠标左击时,获取当前鼠标在图片中的坐标,
 36         m_isMove = true;//标记鼠标左键被按下
 37     }
 38     else if(event->button() == Qt::RightButton)
 39     {
 40         ResetItemPos();//右击鼠标重置大小
 41     }
 42 
 43 }
 44 
 45 void ImageWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
 46 {
 47     if(m_isMove)
 48     {
 49         QPointF point = (event->pos() - m_startPos)*m_scaleValue;
 50         moveBy(point.x(), point.y());
 51     }
 52 }
 53 
 54 void ImageWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *)
 55 {
 56     m_isMove = false;//标记鼠标左键已经抬起
 57 }
 58 
 59 
 60 void ImageWidget::wheelEvent(QGraphicsSceneWheelEvent *event)//鼠标滚轮事件
 61 {
 62     if((event->delta() > 0)&&(m_scaleValue >= 50))//最大放大到原始图像的50倍
 63     {
 64         return;
 65     }
 66     else if((event->delta() < 0)&&(m_scaleValue <= m_scaleDafault))//图像缩小到自适应大小之后就不继续缩小
 67     {
 68         ResetItemPos();//重置图片大小和位置,使之自适应控件窗口大小
 69     }
 70     else
 71     {
 72         qreal qrealOriginScale = m_scaleValue;
 73         if(event->delta() > 0)//鼠标滚轮向前滚动
 74         {
 75             m_scaleValue*=1.1;//每次放大10%
 76         }
 77         else
 78         {
 79             m_scaleValue*=0.9;//每次缩小10%
 80         }
 81         setScale(m_scaleValue);
 82         if(event->delta() > 0)
 83         {
 84             moveBy(-event->pos().x()*qrealOriginScale*0.1, -event->pos().y()*qrealOriginScale*0.1);//使图片缩放的效果看起来像是以鼠标所在点为中心进行缩放的
 85         }
 86         else
 87         {
 88             moveBy(event->pos().x()*qrealOriginScale*0.1, event->pos().y()*qrealOriginScale*0.1);//使图片缩放的效果看起来像是以鼠标所在点为中心进行缩放的
 89         }
 90     }
 91 }
 92 
 93 void ImageWidget::setQGraphicsViewWH(int nwidth, int nheight)//将主界面的控件QGraphicsView的width和height传进本类中,并根据图像的长宽和控件的长宽的比例来使图片缩放到适合控件的大小
 94 {
 95     int nImgWidth = m_pix.width();
 96     int nImgHeight = m_pix.height();
 97     qreal temp1 = nwidth*1.0/nImgWidth;
 98     qreal temp2 = nheight*1.0/nImgHeight;
 99     if(temp1>temp2)
100     {
101         m_scaleDafault = temp2;
102     }
103     else
104     {
105         m_scaleDafault = temp1;
106     }
107     setScale(m_scaleDafault);
108     m_scaleValue = m_scaleDafault;
109 }
110 
111 void ImageWidget::ResetItemPos()//重置图片位置
112 {
113     m_scaleValue = m_scaleDafault;//缩放比例回到一开始的自适应比例
114     setScale(m_scaleDafault);//缩放到一开始的自适应大小
115     setPos(0,0);
116 }
117 
118 qreal ImageWidget::getScaleValue() const
119 {
120     return m_scaleValue;
121
相关推荐
沐泽Mu几秒前
嵌入式学习-QT-Day07
c++·qt·学习·命令模式
沐泽Mu2 分钟前
嵌入式学习-QT-Day09
开发语言·qt·学习
小猿_007 分钟前
C语言实现顺序表详解
c语言·开发语言
ALISHENGYA9 分钟前
全国青少年信息学奥林匹克竞赛(信奥赛)备考实战之分支结构(实战训练三)
数据结构·c++·算法·图论
余~~1853816280027 分钟前
NFC 碰一碰发视频源码搭建技术详解,支持OEM
开发语言·人工智能·python·音视频
GOATLong39 分钟前
c++智能指针
开发语言·c++
Dola_Pan1 小时前
C语言:随机读写文件、实现文件复制功能
c语言·开发语言
佳心饼干-1 小时前
C语言-08复合类型-结构体
c语言·开发语言
帅逼码农1 小时前
python爬虫代码
开发语言·爬虫·python·安全架构