Issue
I'm new to QFileSystemModel class but I'm confused with the functions of setRootPath and setRootIndex
Solution
QFileSystemModel
is a model and inherits from QAbstractItemModel
, so each element of the structure has a QModelIndex
associated with it
from http://doc.qt.io/qt-5/model-view-programming.html#basic-concepts:
The QModelIndex is a temporary representation of the items that stores the information of its location within the structure.
In the case of QFileSystemModel
is a model of type tree so it has as root a QModelIndex
, and this can represent any directory, so to establish what is the root there is the setRootPath()
method:
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.
But also keep in mind that a model can be used by several views, and each view could show different sub-parts of the model (for example different sub-directories) so the rootIndex()
of the model should not be the root that is shown in the view. To do this, the views that inherit from QAbstractItemView
have the setRootIndex()
method:
void QAbstractItemView::setRootIndex(const QModelIndex & index)
Sets the root item to the item at the given index.
In conclusion, the QFileSystemModel
has a rootPath
that indicates the root from where the files will be monitored, and the views have a rootIndex
that tells them which part of the model to show.
Example:
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_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.