filewidget.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from PySide2 import QtCore, QtGui, QtWidgets
  2. from PySide2.QtWidgets import (QWidget, QLabel, QApplication,
  3. QHBoxLayout, QVBoxLayout, QFormLayout,QStyle )
  4. from PySide2.QtGui import QPixmap,QIcon,Qt
  5. class FileWidget(QWidget):
  6. icons = {
  7. "Folder": QStyle.SP_DirIcon,
  8. "File": QStyle.SP_FileIcon
  9. }
  10. def __init__(self, text, filetype, height=17):
  11. super().__init__()
  12. self.setFixedHeight(height)
  13. # self.setStyleSheet("*{margin:0px;border: 1px solid red}")
  14. self.text = text
  15. self.type = filetype
  16. self.icon = QLabel(self)
  17. self.icon.setFixedHeight(self.height())
  18. self.fileName = QLabel(self)
  19. self.fileName.setMargin(0)
  20. self.fileName.setAlignment(Qt.AlignmentFlag.AlignVCenter)
  21. self.setLayout(QFormLayout())
  22. self.layout().setMargin(0)
  23. # QFormLayout().setFormAlignment(Qt.AlignmentFlag.AlignTop)
  24. self.layout().setFormAlignment(Qt.AlignmentFlag.AlignTop)
  25. self.layout().setWidget(0, QtWidgets.QFormLayout.LabelRole, self.icon)
  26. self.layout().setWidget(0, QtWidgets.QFormLayout.FieldRole, self.fileName)
  27. self.set_icon()
  28. self.fileName.setText(text)
  29. def get_text(self):
  30. return self.text
  31. def set_icon(self):
  32. QStyle_SP_ICON = self.icons.get(self.type)
  33. if not QStyle_SP_ICON:
  34. # 在 file_list.py 中会有其它类型的文件,如:MP3,doc,video 等,图标默认只显示 File 即可
  35. QStyle_SP_ICON = self.icons.get("File")
  36. icon = QIcon(QApplication.style().standardIcon(QStyle_SP_ICON))
  37. m_pix = icon.pixmap(self.icon.size())
  38. self.icon.setPixmap(m_pix)
  39. self.icon.setScaledContents(True)
  40. if __name__ == "__main__":
  41. import sys
  42. app = QtWidgets.QApplication(sys.argv)
  43. Form = FileWidget("Sample Folder", "Folder")
  44. Form.show()
  45. sys.exit(app.exec_())