在前一文中有講到的基本用法,詳細可以參看:106.——PyQt5 基本用法實例。本文主要想通過實例演示一下組件用法打開文件對話框類是打開文件對話框類是,它主要用來以列表形式來呈現(xiàn)數(shù)據(jù)。
實現(xiàn)想法:獲取當前目錄下的圖像文件路徑,并在中呈現(xiàn),選擇文件,顯示圖像。
一、界面設計
兩個元素:一個組件:名稱:,一個label組件:名稱:,用來顯示圖像。(頁面布局自適應)
UI
二、功能實現(xiàn)
1、PyQt應用程序基本框架代碼:
包含基本引用、主窗口類、程序入口。
import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_listview import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)

if __name__ == '__main__':
app=QtWidgets.QApplication(sys.argv)
MyWindow=MainWindow()
MyWindow.setWindowTitle('ListView')
MyWindow.show()
sys.exit(app.exec_())
2、功能實現(xiàn)(完整代碼)
import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_listview import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self):
super().__init__()

self.setupUi(self)
#獲取當前目錄
curdir=os.path.abspath(os.curdir)
#獲取當前目錄下的所有圖片文件
lstimg=["選擇文件夾"]
for root,dir,file in os.walk(curdir):
for f in file:
if os.path.splitext(f)[1] in ['.jpg','.png','.bmp']:
lstimg.append(os.path.join(root,f))
#把圖片文件列表放到listview中
slm=QtCore.QStringListModel()
slm.setStringList(lstimg)
self.lstimg.setModel(slm)

# label控件的鼠標注單擊事件(沒有槽函數(shù))
self.lblimg.mousePressEvent=self.lblimg_clicked
#圖片列表單擊事件
def on_lstimg_clicked(self,index):
#獲取當前圖片文件名
self.imgname=self.lstimg.model().stringList()[index.row()]
if self.imgname=="選擇文件夾":
#打開選擇文件夾對話框
dirname=QtWidgets.QFileDialog.getExistingDirectory(self,'選擇文件夾')
lstimg=["選擇文件夾"]
for root,dir,file in os.walk(dirname):
for f in file:
if os.path.splitext(f)[1] in ['.jpg','.png','.bmp']:
lstimg.append(os.path.join(root,f))
#把圖片文件列表放到listview中

slm=QtCore.QStringListModel()
slm.setStringList(lstimg)
self.lstimg.setModel(slm)
else:
#設置lblimg的大小和位置
self.lblimg.setGeometry(self.lstimg.width()+10,0,self.width()-self.lstimg.width(),self.lstimg.height())
#設置圖像大小自適應控件大小并顯示圖像
self.lblimg.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(self.imgname)).scaled(self.lblimg.width(),
self.lblimg.height(),QtCore.Qt.KeepAspectRatio))
self.statusBar().showMessage(self.imgname)
#圖片單擊事件
def lblimg_clicked(self,event):
#獲取當前圖片大小
#獲取圖像的寬高
img=QtGui.QImage(self.imgname)
h,w,c=img.height(),img.width(),img.format()

self.statusBar().showMessage("(w,h,c):"+str(w)+","+str(h)+","+str(c))
if __name__ == '__main__':
app=QtWidgets.QApplication(sys.argv)
MyWindow=MainWindow()
MyWindow.setWindowTitle('ListView')
MyWindow.show()
sys.exit(app.exec_())
三、運行效果
選擇圖像文件,顯示圖像
選擇圖像文件,顯示圖像
單擊圖像,顯示圖像大小
本文也只是演示一下組件+Label顯示圖像的基本用法,更多用法可以參看幫助文檔。