64 lines
No EOL
2.3 KiB
Python
64 lines
No EOL
2.3 KiB
Python
import sys
|
||
from pathlib import Path
|
||
from PyQt6.QtWidgets import (
|
||
QApplication, QWidget, QHBoxLayout, QListWidget, QLabel, QFileDialog
|
||
)
|
||
from PyQt6.QtGui import QPixmap
|
||
from PyQt6.QtCore import Qt
|
||
|
||
class ImageViewer(QWidget):
|
||
def __init__(self):
|
||
super().__init__()
|
||
self.setWindowTitle("Image Viewer")
|
||
self.resize(800, 600)
|
||
|
||
self.layout = QHBoxLayout(self)
|
||
|
||
# Список файлов
|
||
self.file_list = QListWidget()
|
||
self.file_list.itemClicked.connect(self.display_image)
|
||
self.layout.addWidget(self.file_list, 1)
|
||
|
||
# Область для изображения
|
||
self.image_label = QLabel("Выберите файл")
|
||
self.image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||
self.layout.addWidget(self.image_label, 3)
|
||
|
||
# Открыть директорию
|
||
self.open_directory()
|
||
|
||
def open_directory(self):
|
||
dir_path = QFileDialog.getExistingDirectory(self, "Выберите папку с изображениями")
|
||
if not dir_path:
|
||
return
|
||
self.files = list(Path(dir_path).glob("*.[pj][np][gmb]*")) # png/jpg/jpeg/bmp/gif
|
||
self.file_list.clear()
|
||
for file in self.files:
|
||
self.file_list.addItem(file.name)
|
||
|
||
def display_image(self, item):
|
||
index = self.file_list.row(item)
|
||
file_path = self.files[index]
|
||
pixmap = QPixmap(str(file_path))
|
||
if pixmap.isNull():
|
||
self.image_label.setText("Не удалось открыть изображение")
|
||
return
|
||
# Подгонка изображения под размер QLabel с сохранением пропорций
|
||
pixmap = pixmap.scaled(
|
||
self.image_label.size(),
|
||
Qt.AspectRatioMode.KeepAspectRatio,
|
||
Qt.TransformationMode.SmoothTransformation
|
||
)
|
||
self.image_label.setPixmap(pixmap)
|
||
|
||
# Чтобы изображение подгонялось при изменении размера окна
|
||
def resizeEvent(self, event):
|
||
if self.image_label.pixmap():
|
||
self.display_image(self.file_list.currentItem())
|
||
super().resizeEvent(event)
|
||
|
||
if __name__ == "__main__":
|
||
app = QApplication(sys.argv)
|
||
viewer = ImageViewer()
|
||
viewer.show()
|
||
sys.exit(app.exec()) |