how to create folder view in pyqt inside main window

后端 未结 2 1217
Happy的楠姐
Happy的楠姐 2020-12-09 22:19

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 dia

相关标签:
2条回答
  • 2020-12-09 22:37

    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_())
    
    0 讨论(0)
  • 2020-12-09 22:43

    for PyQt5 I did this function :

    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 :

    0 讨论(0)
提交回复
热议问题