QFileSystemModel中setRootPath和setRootIndex的区别

Difference between setRootPath and setRootIndex in QFileSystemModel

我是 QFileSystemModel 的新手 class 但我对 setRootPath 和 setRootIndex 的功能感到困惑

QFileSystemModel是一个模型,继承自QAbstractItemModel,所以结构的每个元素都有一个QModelIndex与之关联

来自 http://doc.qt.io/qt-5/model-view-programming.html#basic-concepts:

QModelIndex 是项目的临时表示,存储其在结构中的位置信息。

如果 QFileSystemModel 是树型模型,所以它的根是 QModelIndex,这可以表示任何目录,所以要确定什么是根,有 setRootPath()方法:

QModelIndex QFileSystemModel::setRootPath(const QString &newPath)

Sets the directory that is being watched by the model to newPath by installing a file system watcher on it. Any changes to files and directories within this directory will be reflected in the model.

If the path is changed, the rootPathChanged() signal will be emitted.

Note: This function does not change the structure of the model or modify the data available to views. In other words, the "root" of the model is not changed to include only files and directories within the directory specified by newPath in the file system.

但也要记住,一个模型可以被多个视图使用,每个视图可以显示模型的不同子部分(例如不同的子目录),所以模型的 rootIndex()不应是视图中显示的根。为此,从 QAbstractItemView 继承的视图具有 setRootIndex() 方法:

void QAbstractItemView::setRootIndex(const QModelIndex & index)

Sets the root item to the item at the given index.

总而言之,QFileSystemModel 有一个 rootPath 指示文件将被监视的根目录,而视图有一个 rootIndex 告诉他们文件的哪一部分要显示的模型。

示例:

import sys

from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import QFileSystemModel, QTreeView, QWidget, QHBoxLayout, QApplication

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    lay = QHBoxLayout(w)
    model = QFileSystemModel()
    model.setRootPath(QDir.rootPath())
    for dirname in (QDir.rootPath(), QDir.homePath(), QDir.currentPath()):
        view = QTreeView()
        view.setModel(model)
        view.setRootIndex(model.index(dirname))
        lay.addWidget(view)
    w.show()

    sys.exit(app.exec_())