简体   繁体   English

如何在主窗口内的pyqt中创建文件夹视图

[英]how to create folder view in pyqt inside main window

I'm trying to implement a folder viewer to view the structure of a specific path. 我正在尝试实现文件夹查看器来查看特定路径的结构。 and this folder view should look like a the tree widget in PyQT , i know that the file dialog can help , but i need to have it inside my main window. 这个文件夹视图应该看起来像PyQT中的树小部件,我知道文件对话框可以帮助,但我需要在我的主窗口中。
i tried to implement this using QTreeWidget and i used a recursed function to loop inside folders, but this is too slow. 我试图使用QTreeWidget实现这一点,我使用一个递归函数循环文件夹,但这太慢了。 since it needs to recurse around huge number of folders. 因为它需要递归大量的文件夹。 is this the right way to do it? 这是正确的方法吗? or there is a ready qt solution for this problem. 或者有一个现成的qt解决方案来解决这个问题。
Check the figure below. 检查下图。


在此输入图像描述

for PyQt5 I did this function : 对于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'))

then i call it like this : 然后我称之为:

 load_project_structure("/your/path/here",projectTreeWidget)

and i have this result : 我有这个结果: 在此输入图像描述

Use models and views. 使用模型和视图。

"""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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM