本文主要是想体验一下ListView多选功能,实现图像文件多选,并同时在窗体上显示图像效果。
一个ListView组件,用来显示图像文件列表,一个Label组件,用来显示图片。
实现的主要思想:
根据列表多选返回的图像文件的数量和路径,把Label等分成平方数量,如(1,4,9,16,……),主要是方便计算图像展示的坐标位置,然后通过图像ROI操作,把所有的图片显示在label组件上。
import sysfrom PyQt5 import QtCore, QtGui, QtWidgetsfrom Ui_showimg import Ui_MainWindowimport osimport cv2import numpy as npclass MainWindow(QtWidgets.QMainWindow,Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.lstimg.clicked.connect(self.on_lstimg_clicked) #设置列表框多选 self.lstimg.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) curdir=os.path.abspath(os.curdir) imglst=["选择文件夹"] for root,dir,file in os.walk(curdir): for f in file: if f.endswith(".jpg") or f.endswith(".png"): imglst.append(os.path.join(root,f)) slm=QtCore.QStringListModel() slm.setStringList(imglst) self.lstimg.setModel(slm) #设置lstimg的宽高 self.lstimg.setFixedSize(self.width()//3,self.height()-self.statusbar.height()) #列表框选择事件 def on_lstimg_clicked(self,index): #获取选择的图片名称 imgnamelst=[] imgname=self.lstimg.model().stringList()[index.row()] if imgname=="选择文件夹": #打开选择文件夹对话框,选择图片文件夹 dirname=QtWidgets.QFileDialog.getExistingDirectory(self,"选择文件夹",".") imglst=["选择文件夹"] for root,dir,file in os.walk(dirname): for f in file: if f.endswith(".jpg") or f.endswith(".png"): imglst.append(os.path.join(root,f)) #把图片文件列表放到listview中 slm=QtCore.QStringListModel() slm.setStringList(imglst) self.lstimg.setModel(slm) else: for i in self.lstimg.selectedIndexes(): f=self.lstimg.model().stringList()[i.row()] imgnamelst.append(f) #print(imgnamelst) if len(imgnamelst)>0: self.showimg(imgnamelst) def showimg(self,imgname:list): #设置lbimg的宽高 self.lblimg.setFixedSize(self.width()-self.lstimg.width(),self.height()-self.statusbar.height()) #标签内容为center,图片居中显示 self.lblimg.setAlignment(QtCore.Qt.AlignCenter) #创建一个空的图片,用于显示图片 img=np.ones((self.lblimg.height(),self.lblimg.width(),3),np.uint8)*255 d=int(np.sqrt([len(imgname)])) #图片数量 if np.sqrt([len(imgname)])-d>0: #图片数量不是平方数 d=d+1 w=self.lblimg.width()//d #每张图片的宽度 h=self.lblimg.height()//d #每张图片的高度 #print(d,w,h) for i,f in enumerate(imgname): fimg=cv2.imread(f) fimg=cv2.resize(fimg,(w,h)) #self.lblimg.setScaledContents(True) r,c=(i // d),(i % d) #print(i,r,c,img.shape,w,h) img[r*h:h+r*h,c*w:w+c*w]=fimg[:,:] img= QtGui.QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 3,QtGui.QImage.Format_BGR888) #按比例缩放图片 self.lblimg.setPixmap(QtGui.QPixmap.fromImage(img).scaled(self.lblimg.width(), self.lblimg.height(),QtCore.Qt.KeepAspectRatio)) #自适应大小 #self.label.setScaledContents(True)if __name__ == '__main__': app=QtWidgets.QApplication(sys.argv) window=MainWindow() window.setWindowTitle("showimg") window.show() sys.exit(app.exec_())本文主要是提供图像文件多选多显示的一种思路方式。
| 留言与评论(共有 0 条评论) “” |