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

1. 工程配置文件 pro

1 QT       += core gui2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets4 5 CONFIG += c++116 7 # The following define makes your compiler emit warnings if you use8 # any Qt feature that has been marked deprecated (the exact warnings9 # 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

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

1 #ifndef MAINWINDOW_H2 #define MAINWINDOW_H3 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

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

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

1 #ifndef IMAGEWIDGET_H2 #define IMAGEWIDGET_H3 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

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() const20 {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     else71     {72         qreal qrealOriginScale = m_scaleValue;73         if(event->delta() > 0)//鼠标滚轮向前滚动74         {75             m_scaleValue*=1.1;//每次放大10%76         }77         else78         {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         else87         {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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/770503.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用免费ChatGPT提升工作效率

ChatGPT无限次数: 点击直达 智能工作利器ChatGPT&#xff1a;提升工作效率 在当今信息爆炸的时代&#xff0c;快速高效地撰写论文对于科研工作者来说至关重要。智能工具ChatGPT的出现为我们提供了强大的支持&#xff0c;它不仅能够提升工作的效率&#xff0c;还能够帮助我们更…

Oracle 使用PLSQL 导出 一个表的insert 语句

1. 使用工具 plsql 的方法,如图示 2. 操作界面(按ctrl键鼠标可多选表) 3. 然后就看到了插入语句 原文&#xff1a;https://www.cnblogs.com/jinanxiaolaohu/p/9192766.html

基于直方图相似性的图像分类算法FPGA实现,包括tb测试文件和MATLAB辅助验证

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 5.算法完整程序工程 1.算法运行效果图预览 MATLAB测试结果&#xff1a; FPGA测试结果&#xff1a; 上述仿真图中&#xff0c;红色XX表示图像读取完毕。因此输出XX。当图像输出完成之后&…

Elasticsearch 索引模板、生命周期策略、节点角色

简介 索引模板可以帮助简化创建和二次配置索引的过程&#xff0c;让我们更高效地管理索引的配置和映射。 索引生命周期策略是一项有意义的功能。它通常用于管理索引和分片的热&#xff08;hot&#xff09;、温&#xff08;warm&#xff09;和冷&#xff08;cold&#xff09;数…

科技类媒体邀约资源有哪些?科技公司做活动如何做好宣传?

传媒如春雨&#xff0c;润物细无声&#xff0c;大家好&#xff0c;我是51媒体网胡老师。 科技类媒体邀约资源包括了各类专注于科技报道的平台和渠道&#xff0c;科技公司可以通过多样化的宣传策略来提升活动的影响力。 科技类媒体资源的邀约通常涉及多种不同的平台和形式&…

基于nodejs+vue高校自习室预约系统的设计与实现python-flask-django-php

本系统在设计过程中&#xff0c;很好地发挥了该开发方式的优势&#xff0c;让实现代码有了良好的可读性&#xff0c;而且使代码的更新和维护更加的方便&#xff0c;操作简单&#xff0c;对以后的维护减少了很多麻烦。系统的顺利开发和实现&#xff0c;对于高校自习室预约这一方…

命令模式(请求与具体实现解耦)

目录 前言 UML plantuml 类图 实战代码 模板 Command Invoker Receiver Client 前言 命令模式解耦了命令请求者&#xff08;Invoker&#xff09;和命令执行者&#xff08;receiver&#xff09;&#xff0c;使得 Invoker 不再直接引用 receiver&#xff0c;而是依赖于…

msvcp100.dll是什么东西?电脑msvcp100.dll丢失的六种解决方法

最近&#xff0c;我在电脑上打开一款软件时&#xff0c;遇到了一个问题&#xff1a;找不到msvcp100.dll丢失问题&#xff0c;为了解决这个问题&#xff0c;我进行了深入的学习和研究&#xff0c;并在此分享msvcp100.dll丢失的解决方法。 一&#xff0c;msvcp100.dll是什么&…

AI:133-基于深度学习的工业质检自动化

AI&#xff1a;133-基于深度学习的工业质检自动化 1.背景介绍 随着工业自动化水平的不断提高&#xff0c;工业质检成为了一个重要的环节。传统的工业质检主要依靠人工进行&#xff0c;不仅效率低下&#xff0c;而且容易受到主观因素的影响。近年来&#xff0c;随着深度学习技…

Visual Studio QT6 工程引入组件模块,例如:QtXml

QT 工程引入 QtXml QT 版本 6.6.1 Visual Studio 版本 Microsoft Visual Studio Community 2022 (64 位) - Current 版本 17.7.5 打开 Visual Studio 项目工程选择 工具栏 - 扩展 - QT VS Tools -Qt Project Settings 勾选 xml 后点击确定 点击应用即可 注意&#xff1a;配置环…

Apache Dolphinscheduler - 执行工作流却没有创建任务实例分析

问题描述 最近碰到一个奇怪的问题&#xff0c;DS 创建工作流成功&#xff0c;但是一旦执行&#xff0c;始终在转&#xff0c;而且没有任何执行的痕迹&#xff0c;后来到数据库一查发现压根没创建任务实例。 我们都知道一个工作流里面可以挂多个任务节点&#xff0c;执行工作流…

Windows蓝牙驱动开发之模拟HID设备(二)(把Windows电脑模拟成蓝牙鼠标和蓝牙键盘等设备)

by fanxiushu 2024-03-24 转载或引用请注明原作者 接上文,当我们建立了蓝牙链接请求之后,就该传输数据了, 其实传输数据比起上章阐述的创建SDP和建立连接要简单许多。 使用类型 BRB_L2CA_ACL_TRANSFER 的BRB请求,就可以实现接收和发送操作, 至于具体是接收还是发送,根据设…

Python 全栈体系【四阶】(十九)

第五章 深度学习 一、基本理论 4. 神经网络的改进 4.3 循环神经网络 4.3.1 标准 CNN 模型的不足 假设数据之间是独立的。标准 CNN 假设数据之间是独立的&#xff0c;所以在处理前后依赖、序列问题&#xff08;如语音、文本、视频&#xff09;时就显得力不从心。这一类数据…

华为校招机试 - 计算座位最大利用数(20240320)

题目描述 一列具有 m 个座位的火车,从起点到终点共停靠 n 个站点,站点编号从 0 到 n - 1。 发车前有 x 名乘客预定了座位,因为预定数量可能超出座位数,为了保证效率最大化,请计算如何分配才能是座位利用率最大,并输出最大的座位利用数。 说明: 座位利用数定义为每个座…

iOS - Runtime-isa详解(位域、union(共用体)、位运算)

文章目录 iOS - Runtime-isa详解&#xff08;位域、union&#xff08;共用体&#xff09;、位运算&#xff09;前言1. 位域介绍1.1 思路1.2 示例 - 结构体1.3 示例 - union&#xff08;共用体&#xff09;1.3.1 说明 1.4 结构体 对比 union&#xff08;共用体&#xff09; 2. a…

【前端】代码案例

1.猜数字 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>猜数字</title> </head> <…

HS6621低功耗蓝牙SoC芯片应用于键盘鼠标和遥控器消费类产品

HS6621Cx是一款功耗优化的真正片上系统 (SOC)解决方案&#xff0c;适用于低功耗蓝牙和专有2.4GHz应用。它集成了高性能、低功耗射频收发器&#xff0c;具有蓝牙基带和丰富的外设IO扩展。HS6621Cx还集成了电源管理功能&#xff0c;可提供高效的电源管理。它面向2.4GHz蓝牙低功耗…

idea运行项目没反应【debug和run灰色】

解决方法 File->Settings->Plugins->groovy 将groovy勾选的√去掉&#xff0c;保存再重新启动idea即可。 啊啊啊码

【微服务】认识Dubbo+基本环境搭建

认识Dubbo Dubbo是阿里巴巴公司开源的一个高性能、轻量级的WEB和 RPC框架&#xff0c;可以和Spring框架无缝集成。Dubbo为构建企业级微服务提供了三大核心能力&#xff1a; 服务自动注册和发现、面向接口的 远程方法调用&#xff0c; 智能容错和负载均衡官网&#xff1a;https…

RK3568平台 iperf3测试网络性能

一.iperf3简介 iperf是一款开源的网络性能测试工具&#xff0c;主要用于测量TCP和UDP带宽性能。它可以在不同的操作系统上运行&#xff0c;包括Windows、Linux、macOS等。iperf具有简单易用、功能强大、高度可配置等特点&#xff0c;广泛应用于网络性能测试、网络故障诊断和网…