Solved Unexpected behavior of QFileSystemModel
-
@midnightdim
This is not good! :( Assuming your filing system on D: is the same as on C:, plus it's a local drive, both of which I imagine are the case.Any chance of testing it from PySide2 or even PyQt5/6? If it's really an issue, I imagine it will lie in
QFileSystemModel
(perhaps under Qt6), rather than being anything Python/PySide/PyQt related.... -
@JonB I tried to quickly port to PySide2, but ran into some issues.
I could port it to PyQt6, and I could reproduce this issue.
So it looks like this problem lies deeper. I'll check if I can reports this bug in Qt bug tracker. -
@midnightdim
Shame you couldn't have tried PyQt5. Your usage looks OK, andQFileSystemModel
must work right in versions of Qt prior to 6? -
@JonB I found a bug that looks kind of similar: https://bugreports.qt.io/browse/QTBUG-12934
But it's closed as invalid. -
@midnightdim
Yes, that is indeed your situation. But it's closed/invalid because you need to read what the comments say and make yourQFileSystemModel::rootPath
line up with yourQTreeView::setRootIndex()
. -
@JonB OK, this is exactly the same issue that was described in https://bugreports.qt.io/browse/QTBUG-12934
When I set the root path to "" and have the full tree displayed, and then I expand the first drive
C:
all folders look as expected.
However, all folders under other drives have files and folders mixed - exactly like on the screenshots attached to the issue.I don't fully understand the solution. The comment before the last one says:
But it's not a bug imho.
The user explicitly sets the QFileSystemModel::rootPath to be a sub-tree of the model (C:\ in this case).
Now he is supposed to use QTreView::setRootIndex() to show only the sub-tree, D:'s sorting becomes a moot point because it's hidden.What exactly should be updated in the code to have this resolved? It's not clear from setRootIndex documentation for QTreeView.
-
@JonB Here's how I'm using it:
path = r"D:\Downloads" self.model = QFileSystemModel() self.model.setRootPath((QDir.rootPath())) self.ui.treeView.setModel(self.model) self.ui.treeView.setRootIndex(self.model.index(path))
It seems to correspond to what that ticket suggests.
-
OK, I found my mistake. It should be:
path = r"D:\Downloads" self.model = QFileSystemModel() self.model.setRootPath(path) self.ui.treeView.setModel(self.model) self.ui.treeView.setRootIndex(self.model.index(path))
I.e. root path should be set to the same folder. Thanks for your support.
-
@midnightdim
Good stuff.As a small tip: Qt pathnames (for Qt functions expecting a pathname) are best always written using
/
s instead of\
s, on every platform, even Windows.path = "D:/Downloads"
. The same for Python'spathlib
. Tends to work with backslashes, but can be "gotchas", so use forward always. -
@JonB Thanks. I use
os.path.normpath
everywhere to get rid of this kind of problems :)