参考:QFileDialog 的文档,完成对某个目录下的多个图片文件的选择。然后,结合使 用 QLabel/QImage/QPixmap 来显示图片的示例项目 viewer-demo,实现图片的依次浏览,此时按下 space/ backspace 键,或者用鼠标点击 next/previous 菜单项,可以切换显示下一张/上一张图片;当浏览到最后/第 一张图片时,程序给出相应的提示
时间: 2024-01-22 20:03:46 浏览: 26
下面是一个实现该功能的示例代码:
```python
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QAction, QLabel
from5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import Qt
class ImageViewer(QMainWindow):
def __init__(self):
super().__init__()
# 创建显示图片的标签
self.image_label = QLabel(self)
self.image_label.setAlignment(Qt.AlignCenter)
self.setCentralWidget(self.image_label)
# 创建菜单栏
menubar = self.menuBar()
file_menu = menubar.addMenu('&File')
# 添加打开文件动作
open_action = QAction(QIcon('open.png'), '&Open', self)
open_action.setShortcut('Ctrl+O')
open_action.triggered.connect(self.open_file)
file_menu.addAction(open_action)
# 添加下一张图片动作
next_action = QAction(QIcon('next.png'), '&Next', self)
next_action.setShortcut('Space')
next_action.triggered.connect(self.next_image)
file_menu.addAction(next_action)
# 添加上一张图片动作
prev_action = QAction(QIcon('prev.png'), '&Previous', self)
prev_action.setShortcut('Backspace')
prev_action.triggered.connect(self.prev_image)
file_menu.addAction(prev_action)
# 初始化图片列表和当前显示图片下标
self.image_list = []
self.current_index = -1
def open_file(self):
# 打开文件对话框选择多个图片文件
file_dialog = QFileDialog(self, 'Open Images', filter='Image Files (*.png *.jpg *.bmp)')
file_dialog.setFileMode(QFileDialog.ExistingFiles)
if file_dialog.exec_() == QFileDialog.Accepted:
# 获取选择的文件列表
file_list = file_dialog.selectedFiles()
# 读取图片文件并添加到图片列表
for file_path in file_list:
if os.path.isfile(file_path):
image = QImage(file_path)
if not image.isNull():
self.image_list.append(image)
# 显示第一张图片
if len(self.image_list) > 0:
self.current_index = 0
self.show_image()
def show_image(self):
# 显示当前图片
image = self.image_list[self.current_index]
pixmap = QPixmap.fromImage(image)
self.image_label.setPixmap(pixmap)
# 更新窗口标题
self.setWindowTitle(f'Image Viewer - {self.current_index + 1}/{len(self.image_list)}')
def next_image(self):
# 显示下一张图片
if len(self.image_list) > 0:
self.current_index = (self.current_index + 1) % len(self.image_list)
self.show_image()
def prev_image(self):
# 显示上一张图片
if len(self.image_list) > 0:
self.current_index = (self.current_index - 1) % len(self.image_list)
self.show_image()
def keyPressEvent(self, event):
# 监听键盘事件
if event.key() == Qt.Key_Space:
self.next_image()
elif event.key() == Qt.Key_Backspace:
self.prev_image()
else:
super().keyPressEvent(event)
if __name__ == '__main__':
app = QApplication([])
window = ImageViewer()
window.show()
app.exec_()
```
在该示例中,我们首先创建了一个菜单栏,添加了“打开文件”、“下一张图片”和“上一张图片”三个动作。在“打开文件”动作的触发事件中,我们通过打开文件对话框选择多个图片文件,并将它们添加到图片列表中。在“下一张图片”和“上一张图片”动作的触发事件中,我们分别显示下一张和上一张图片,并更新窗口标题。同时,我们还重写了窗口的`keyPressEvent`方法,监听键盘事件,实现按下 space/ backspace 键切换图片的功能。
需要注意的是,如果图片非常大,可能会导致程序卡顿。在实际开发中,我们可以使用多线程或异步加载的方式来加载和显示图片,提高程序的性能和用户体验。