【问题标题】:Change Root Path of Model during runtime - PyQt5在运行时更改模型的根路径 - PyQt5
【发布时间】:2020-02-28 02:35:33
【问题描述】:

我有一个 QWidget,我在其中使用 QTreeView 和 QFileSystemModel。

我创建了一个接收路径的函数。如果它是有效路径,我希望 TreeView 将其根更新为给定路径。

到目前为止,这部分工作完美无缺。但是如果没有给出路径,我想把 TreeView 恢复到原来的状态。

这部分我无法解决。

问题是,更新 TreeView 需要什么?

我的示例代码是:

import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc


class FolderView(qtw.QWidget):
    def __init__(self):
        super().__init__()
        self.init_me()

    def init_me(self):
        self.model = qtw.QFileSystemModel()
        home_location = qtc.QStandardPaths.standardLocations(qtc.QStandardPaths.HomeLocation)[0]
        self.index = self.model.setRootPath(home_location)

        self.tree = qtw.QTreeView()
        self.tree.setModel(self.model)
        self.tree.setCurrentIndex(self.index)

        self.tree.setAnimated(False)
        self.tree.setIndentation(20)

        self.tree.setSortingEnabled(True)

        window_layout = qtw.QVBoxLayout()
        window_layout.addWidget(self.tree)

        self.setLayout(window_layout)

        self.show()            

    def set_root(self, path):
        if len(path) == 0:

        ## RETURN BACK TO NORMAL ##
            self.model.setRootPath(path)
            self.tree.setCurrentIndex(self.index)

        else:
        ## ONLY SHOW DATA FROM THE GIVEN PATH ##
            self.tree.setRootIndex(self.model.index(path))

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = FolderView()
    sys.exit(app.exec())

【问题讨论】:

    标签: python-3.x treeview pyqt5 qfilesystemmodel


    【解决方案1】:

    当您打开模型时,默认的rootIndex() 是一个无效 索引。

    通过使用setRootIndex,您实际上是在告诉树使用模型的另一个(可能有效)索引作为其根。

    要恢复到原始形式,您必须将根设置为模型的实际根,这可以通过创建QModelIndex() 的新实例来获得:

    创建一个新的空模型索引。该类型的模型索引用于指示模型中的位置无效。

    因此,解决方案是执行以下操作:

        self.tree.setRootIndex(qtc.QModelIndex())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多