前两天做代码的时候自己实现了一个目录展示的效果,虽然有较强的扩展性,但是官方可能还是要完善一些。
经过几个小时的摸索,大概效果如下:
import sys, os
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout, QDirModelfrom PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIconclass App(QWidget):def __init__(self):super().__init__()self.title = 'PyQt5 file system view - pythonspot.com'self.left = 10self.top = 10self.width = 640self.height = 480self.initUI()def tree_cilcked(self, Qmodelidx):print(self.model.filePath(Qmodelidx))print(self.model.fileName(Qmodelidx))print(self.model.fileInfo(Qmodelidx))def initUI(self):self.setWindowTitle(self.title)self.setGeometry(self.left, self.top, self.width, self.height)# 这里得到目录结构self.model = QFileSystemModel()self.model.setRootPath(QDir.currentPath())# 这里过滤,只显示 py 文件mf = self.model.setNameFilters(['*.py'])self.model.setNameFilterDisables(False)# 这里做展示self.tree = QTreeView()self.tree.setModel(self.model)self.tree.setRootIndex(self.model.index(QDir.currentPath()))self.tree.doubleClicked.connect(self.tree_cilcked)# 这里隐藏了目录信息展示for i in [1,2,3]:self.tree.setColumnHidden(i, True)# 缩进self.tree.setIndentation(10)self.tree.setWindowTitle("Dir View")self.tree.resize(640, 480)windowLayout = QVBoxLayout()windowLayout.addWidget(self.tree)self.setLayout(windowLayout)self.show()if __name__ == '__main__':app = QApplication(sys.argv)ex = App()
效果: