如何在PyQt主窗口中创建文件夹视图
我正在尝试实现一个文件夹查看器,用来查看特定路径下的文件夹结构。这个文件夹视图应该像PyQT中的树形控件一样。我知道文件对话框可以帮忙,但我需要把它放在我的主窗口里。
我试着用QTreeWidget来实现这个功能,并使用了递归函数来遍历文件夹,但这样速度太慢了,因为需要在大量文件夹中递归查找。这样做对吗?或者有没有现成的QT解决方案可以解决这个问题?
请查看下面的图片。
2 个回答
12
对于PyQt5,我写了这个函数:
def load_project_structure(startpath, tree):
"""
Load Project structure tree
:param startpath:
:param tree:
:return:
"""
import os
from PyQt5.QtWidgets import QTreeWidgetItem
from PyQt5.QtGui import QIcon
for element in os.listdir(startpath):
path_info = startpath + "/" + element
parent_itm = QTreeWidgetItem(tree, [os.path.basename(element)])
if os.path.isdir(path_info):
load_project_structure(path_info, parent_itm)
parent_itm.setIcon(0, QIcon('assets/folder.ico'))
else:
parent_itm.setIcon(0, QIcon('assets/file.ico'))
然后我这样调用它:
load_project_structure("/your/path/here",projectTreeWidget)
结果是这样的:

8
使用模型和视图。
"""An example of how to use models and views in PyQt4.
Model/view documentation can be found at
http://doc.qt.nokia.com/latest/model-view-programming.html.
"""
import sys
from PyQt4.QtGui import (QApplication, QColumnView, QFileSystemModel,
QSplitter, QTreeView)
from PyQt4.QtCore import QDir, Qt
if __name__ == '__main__':
app = QApplication(sys.argv)
# Splitter to show 2 views in same widget easily.
splitter = QSplitter()
# The model.
model = QFileSystemModel()
# You can setRootPath to any path.
model.setRootPath(QDir.rootPath())
# List of views.
views = []
for ViewType in (QColumnView, QTreeView):
# Create the view in the splitter.
view = ViewType(splitter)
# Set the model of the view.
view.setModel(model)
# Set the root index of the view as the user's home directory.
view.setRootIndex(model.index(QDir.homePath()))
# Show the splitter.
splitter.show()
# Maximize the splitter.
splitter.setWindowState(Qt.WindowMaximized)
# Start the main loop.
sys.exit(app.exec_())