【问题标题】:how to create folder view in pyqt inside main window如何在主窗口内的pyqt中创建文件夹视图
【发布时间】:2017-05-20 03:08:58
【问题描述】:

我正在尝试实现一个文件夹查看器来查看特定路径的结构。这个文件夹视图应该看起来像 PyQT 中的树小部件,我知道文件对话框可以提供帮助,但我需要将它放在我的主窗口中。
我尝试使用 QTreeWidget 实现这一点,并使用递归函数在文件夹内循环,但这太慢了。因为它需要围绕大量文件夹进行递归。 这是正确的方法吗?或者有一个现成的 qt 解决方案来解决这个问题。
看下图。


【问题讨论】:

    标签: python pyqt pyqt4


    【解决方案1】:

    对于 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)
    

    我有这个结果:

    【讨论】:

    • 我相信你忘了定义projectTreeWidget
    • 是的,抱歉 projectTreeWidget = self.projectTreeWidget 这是一个 QT 小部件参考:
    • 亲爱的@Softmixt 我们如何从 QTreeWidget 获得点击的项目路径?
    • 刚刚找到答案!谢谢你。 github.com/Gordarg/gordarg.github.io/commit/…
    • 我恢复了这个旧答案,因为我不知道如何使用缺失的部分'projectTreeWidget = self.projectTreeWidget'。你能澄清一下它应该去哪里让它工作吗?
    【解决方案2】:

    使用模型和视图。

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

    【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多