PyQt5入門之基于QListWidget版本實現(xiàn)圖片縮略圖列表功能
需求描述
最近在寫一個圖像標(biāo)注小工具,其中需要用到一個縮略圖列表,來查看文件夾內(nèi)的圖片文件。
這里整理一個基于QListWidget實現(xiàn)的版本,簡單可用。
示例效果
代碼示例
QListWidget官方文檔:[link]
其中,需要用到的QListWidget信號:
itemSelectionChanged:所選項發(fā)生變化時發(fā)送。
先定義縮略圖列表部分,繼承自QListWidget。每個QListWidgetItem可以設(shè)置QIcon圖片和文本。
import os from qtpy.QtCore import QSize from qtpy.QtGui import QIcon,QPixmap from PyQt5.QtWidgets import QListWidget,QListWidgetItem,QListView,QWidget,QApplication,QHBoxLayout,QLabel class ImageListWidget(QListWidget): def __init__(self): super(ImageListWidget, self).__init__() self.setFlow(QListView.Flow(1))#0: left to right,1: top to bottom self.setIconSize(QSize(150,100)) def add_image_items(self,image_paths=[]): for img_path in image_paths: if os.path.isfile(img_path): img_name = os.path.basename(img_path) item = QListWidgetItem(QIcon(img_path),img_name) # item.setText(img_name) # item.setIcon(QIcon(img_path)) self.addItem(item)
再來簡單布局下窗體控件:
左邊區(qū)域用QLabel加載圖像,右邊區(qū)域是圖片縮略圖列表,點擊縮略圖,可以在左邊查看大圖。
class ImageViewerWidget(QWidget): def __init__(self): super(QWidget, self).__init__() # 顯示控件 self.list_widget = ImageListWidget() self.list_widget.setMinimumWidth(200) self.show_label = QLabel(self) self.show_label.setFixedSize(600,400) self.image_paths = [] self.currentImgIdx = 0 self.currentImg = None # 水平布局 self.layout = QHBoxLayout(self) self.layout.addWidget(self.show_label) self.layout.addWidget(self.list_widget) # 信號與連接 self.list_widget.itemSelectionChanged.connect(self.loadImage) def load_from_paths(self,img_paths=[]): self.image_paths = img_paths self.list_widget.add_image_items(img_paths) def loadImage(self): self.currentImgIdx = self.list_widget.currentIndex().row() if self.currentImgIdx in range(len(self.image_paths)): self.currentImg = QPixmap(self.image_paths[self.currentImgIdx]).scaledToHeight(400) self.show_label.setPixmap(self.currentImg)
加載一些圖片路徑,并運行窗口:
if __name__=="__main__": import sys app = QApplication(sys.argv) # 圖像路徑 img_dir = r"E:\Pic" filenames = os.listdir(img_dir) img_paths=[] for file in filenames: if file[-4:]==".png" or file[-4:]==".jpg": img_paths.append(os.path.join(img_dir,file)) # 顯示控件 main_widget = ImageViewerWidget() main_widget.load_from_paths(img_paths) main_widget.setWindowTitle("ImageViewer") main_widget.show() # 應(yīng)用程序運行 sys.exit(app.exec_())
小結(jié)
- 上面代碼只是一個實現(xiàn)思路,實際應(yīng)用中最好另開一個線程加載圖片,并且隨著滾動條下拉,再不斷加載緩存。
- QListWidget可以實現(xiàn)簡單的圖標(biāo)+文字列表,如果列表項中涉及自定義控件和其他操作邏輯,建議采用QListView和Model實現(xiàn)。
到此這篇關(guān)于PyQt5入門之QListWidget實現(xiàn)圖片縮略圖列表功能的文章就介紹到這了,更多相關(guān)PyQt5 QListWidget圖片縮略圖內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。