from PySide2 import QtCore, QtGui, QtWidgets from PySide2.QtWidgets import (QWidget, QLabel, QApplication, QHBoxLayout, QVBoxLayout, QFormLayout,QStyle ) from PySide2.QtGui import QPixmap,QIcon,Qt class FileWidget(QWidget): icons = { "Folder": QStyle.SP_DirIcon, "File": QStyle.SP_FileIcon } def __init__(self, text, filetype, height=17): super().__init__() self.setFixedHeight(height) # self.setStyleSheet("*{border: 0.5px solid red}") self.text = text self.type = filetype self.icon = QLabel(self) self.icon.setFixedSize(height-2,height-2) self.fileName = QLabel(self) font = self.fileName.font() font.setPointSizeF(font.pointSizeF() - 0.5) self.fileName.setFont(font) self.setLayout(QFormLayout()) self.layout().setMargin(0) # QFormLayout().setFormAlignment(Qt.AlignmentFlag.AlignTop) self.layout().setFormAlignment(Qt.AlignmentFlag.AlignTop) self.layout().setWidget(0, QtWidgets.QFormLayout.LabelRole, self.icon) self.layout().setWidget(0, QtWidgets.QFormLayout.FieldRole, self.fileName) self.set_icon() self.fileName.setText(text) def get_text(self): return self.text def set_icon(self): QStyle_SP_ICON = self.icons.get(self.type) if not QStyle_SP_ICON: # 在 file_list.py 中会有其它类型的文件,如:MP3,doc,video 等,图标默认只显示 File 即可 QStyle_SP_ICON = self.icons.get("File") icon = QIcon(QApplication.style().standardIcon(QStyle_SP_ICON)) m_pix = icon.pixmap(self.icon.size()) self.icon.setPixmap(m_pix) self.icon.setScaledContents(True) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = FileWidget("Sample Folder", "Folder") Form.show() sys.exit(app.exec_())