qt鼠标悬停图片放大_20.QT-Qpixmap实现图片鼠标缩放,鼠标拖动示例(详解)

时间: 2024-01-24 13:17:25 浏览: 43
在Qt中,可以使用QPixmap来显示图片。要实现图片鼠标缩放和鼠标拖动,可以使用以下步骤: 1. 创建一个QGraphicsView对象,并将其设置为可交互的。 2. 在QGraphicsView中创建一个QGraphicsScene对象,并将其设置为QGraphicsView的场景。 3. 在QGraphicsScene中创建一个QGraphicsPixmapItem对象,并将其设置为QGraphicsScene的项。 4. 加载需要显示的图片并设置到QGraphicsPixmapItem中。 5. 实现鼠标滚轮事件,通过增加或减少QGraphicsPixmapItem的缩放因子来实现图片缩放。 6. 实现鼠标按下和拖动事件,通过改变QGraphicsPixmapItem的位置来实现图片拖动。 下面是具体的代码实现示例: ```cpp #include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsPixmapItem> #include <QPixmap> #include <QWheelEvent> #include <QPointF> #include <QMouseEvent> class ImageView : public QGraphicsView { public: ImageView(QWidget *parent = nullptr) : QGraphicsView(parent) { setInteractive(true); // 设置为可交互的 setDragMode(QGraphicsView::ScrollHandDrag); // 设置拖动模式为滚动拖动 m_pixmapItem = new QGraphicsPixmapItem; m_scene = new QGraphicsScene(this); m_scene->addItem(m_pixmapItem); setScene(m_scene); } void setPixmap(const QPixmap &pixmap) { m_pixmapItem->setPixmap(pixmap); // 设置显示的图片 setSceneRect(pixmap.rect()); // 设置场景大小为图片大小 } protected: void wheelEvent(QWheelEvent *event) override { const QPointF posSceneBefore = mapToScene(event->pos()); // 获取事件发生位置在场景中的位置 const qreal factor = (event->angleDelta().y() > 0) ? 1.1 : 0.9; // 根据鼠标滚轮滚动方向计算缩放因子 m_pixmapItem->setScale(m_pixmapItem->scale() * factor); // 缩放图片 const QPointF posSceneAfter = mapToScene(event->pos()); // 获取事件发生位置在场景中的位置 const QPointF posSceneDelta = posSceneAfter - posSceneBefore; // 计算场景位置的变化 centerOn(mapToScene(viewport()->rect().center()) - posSceneDelta); // 保持鼠标位置不变,调整视图中心 } void mousePressEvent(QMouseEvent *event) override { if (event->button() == Qt::LeftButton) { m_lastPos = event->pos(); // 记录鼠标按下的位置 } QGraphicsView::mousePressEvent(event); } void mouseMoveEvent(QMouseEvent *event) override { if (event->buttons() & Qt::LeftButton) { const QPointF posSceneDelta = mapToScene(event->pos()) - mapToScene(m_lastPos); // 计算场景位置的变化 centerOn(mapToScene(viewport()->rect().center()) - posSceneDelta); // 调整视图中心 m_lastPos = event->pos(); // 记录当前位置,供下次计算使用 } QGraphicsView::mouseMoveEvent(event); } private: QGraphicsPixmapItem *m_pixmapItem; QGraphicsScene *m_scene; QPoint m_lastPos; }; int main(int argc, char *argv[]) { QApplication a(argc, argv); ImageView view; QPixmap pixmap(":/images/image.jpg"); view.setPixmap(pixmap); view.show(); return a.exec(); } ``` 在这个示例中,我们创建了一个ImageView类继承自QGraphicsView。在构造函数中,我们设置了一些初始属性,创建了一个QGraphicsPixmapItem对象和一个QGraphicsScene对象,并将QGraphicsPixmapItem添加到QGraphicsScene中。在setPixmap函数中,我们加载了一张图片,并设置到QGraphicsPixmapItem中。 在wheelEvent函数中,我们根据鼠标滚轮的滚动方向计算缩放因子,并使用setScale函数改变QGraphicsPixmapItem的缩放因子。然后,我们计算视图中心在场景中的位置的变化,并使用centerOn函数调整视图中心,使鼠标位置保持不变。 在mousePressEvent函数和mouseMoveEvent函数中,我们记录了鼠标按下和移动的位置,并根据位置的变化使用centerOn函数调整视图中心,使图片实现拖动效果。 综上所述,通过这种方式,就可以实现图片鼠标缩放和鼠标拖动的效果了。

相关推荐

import os from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QTreeView, QFileSystemModel class ImageViewer(QWidget): def init(self, folder_path): super().init() self.folder_path = folder_path self.image_dict = {} self.current_image = None self.setWindowTitle("Image Viewer") self.setFixedSize(1000, 600) self.image_label = QLabel(self) self.image_label.setAlignment(Qt.AlignCenter) self.tree_view = QTreeView() self.tree_view.setMinimumWidth(250) self.tree_view.setMaximumWidth(250) self.model = QFileSystemModel() self.model.setRootPath(folder_path) self.tree_view.setModel(self.model) self.tree_view.setRootIndex(self.model.index(folder_path)) self.tree_view.setHeaderHidden(True) self.tree_view.setColumnHidden(1, True) self.tree_view.setColumnHidden(2, True) self.tree_view.setColumnHidden(3, True) self.tree_view.doubleClicked.connect(self.tree_item_double_clicked) self.main_layout = QHBoxLayout(self) self.main_layout.addWidget(self.tree_view) self.main_layout.addWidget(self.image_label) self.load_images() self.update_image() def load_images(self): for file_name in os.listdir(self.folder_path): if file_name.lower().endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp")): file_path = os.path.join(self.folder_path, file_name) self.image_dict[file_name] = file_path current_image = list(self.image_dict.keys())[0] def update_image(self): if self.current_image is not None: pixmap = QPixmap(self.image_dict[self.current_image]) self.image_label.setPixmap(pixmap.scaled(self.width() - self.tree_view.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) def tree_item_double_clicked(self, index): file_name = self.model.fileName(index) if file_name in self.image_dict: self.current_image = file_name self.update_image() def keyPressEvent(self, event): if event.key() == Qt.Key_A: self.previous_image() elif event.key() == Qt.Key_D: self.next_image() elif event.key() in [Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5]: self.save_text_file(event.key() - Qt.Key_0) def previous_image(self): if self.current_image is not None: file_names = list(self.image_dict.keys()) current_index = file_names.index(self.current_image) if current_index > 0: self.current_image = file_names[current_index - 1] else: self.current_image = file_names[-1] self.update_image() def next_image(self): if self.current_image is not None: file_names = list(self.image_dict.keys()) current_index = file_names.index(self.current_image) if current_index < len(file_names) - 1: self.current_image = file_names[current_index + 1] else: self.current_image = file_names[0] self.update_image() def save_text_file(self, number): if self.current_image is not None: file_name = self.current_image txt_file_path = os.path.join(self.folder_path, os.path.splitext(file_name)[0] + ".txt") with open(txt_file_path, "w") as file: file.write(str(number)) if name == "main": import sys app = QApplication(sys.argv) viewer = ImageViewer("D:/图片/wallpaper") viewer.show() sys.exit(app.exec_())这份代码实现不了使用键盘的A键向上翻页以及D键向下翻页,也实现不了键盘数字键生成相应txt文档,帮我分析一下错在哪里

修改以下代码使其能够输出模型预测结果: def open_image(self): file_dialog = QFileDialog() file_paths, _ = file_dialog.getOpenFileNames(self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg)") if file_paths: self.display_images(file_paths) def preprocess_images(self, image_paths): data_transform = transforms.Compose([ transforms.CenterCrop(150), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) self.current_image_paths = [] images = [] for image_path in image_paths: image = Image.open(image_path) image = data_transform(image) image = torch.unsqueeze(image, dim=0) images.append(image) self.current_image_paths.append(image_path) return images def predict_images(self): if not self.current_image_paths: return for i, image_path in enumerate(self.current_image_paths): image = self.preprocess_image(image_path) output = self.model(image) predicted_class = self.class_dict[output.argmax().item()] self.result_labels[i].setText(f"Predicted Class: {predicted_class}") self.progress_bar.setValue((i+1)*20) def display_images(self, image_paths): for i, image_path in enumerate(image_paths): image = QImage(image_path) image = image.scaled(300, 300, Qt.KeepAspectRatio) if i == 0: self.image_label_1.setPixmap(QPixmap.fromImage(image)) elif i == 1: self.image_label_2.setPixmap(QPixmap.fromImage(image)) elif i == 2: self.image_label_3.setPixmap(QPixmap.fromImage(image)) elif i == 3: self.image_label_4.setPixmap(QPixmap.fromImage(image)) elif i == 4: self.image_label_5.setPixmap(QPixmap.fromImage(image))

最新推荐

recommend-type

PyQt5 对图片进行缩放的实例

今天小编就为大家分享一篇PyQt5 对图片进行缩放的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

node-v4.1.0-linux-x64.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

输出这段Python代码输出所有3位整数中,个位是5且是3的倍数的整数

``` for i in range(100,1000): if i%10 == 5 and i%3 == 0: print(i) ``` 输出结果: ``` 105 135 165 195 225 255 285 315 345 375 405 435 465 495 525 555 585 615 645 675 705 735 765 795 825 855 885 915 945 975 ```