I had issues making these solutions work for the QML TreeView. I ended up setting the root path of my QFileSystemModel to the directory I wanted to view. Then I set the rootIndex in the TreeView to the parent of the index for that directory. This is of course showed its siblings. Then I did the following to filter those siblings away. I also made this optional through a property as there are times when I want that behavior:
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
FileSystemModel* tmodel = qobject_cast<FileSystemModel*>(parent());
if(tmodel){
QModelIndex index = tmodel->index(source_row, 0, source_parent);
QModelIndex rootIndex = tmodel->index(tmodel->rootPath());
if(!rootIndex.isValid() || !index.isValid())
return false;
return ((index == rootIndex) || !(tmodel->filtersiblings() && isSiblingOf(index, rootIndex)));
}
return false;
}
bool isSiblingOf(const QModelIndex& index, const QModelIndex& parent) const
{
if(!index.isValid() || !parent.isValid())
return false;
QModelIndex sibling;
int row=0;
do{
sibling = parent.sibling(row,0);
if(sibling == index)
return true;
++row;
}while(sibling.isValid());
return false;
}
I took more of a blacklist approach versus a whitelist approach.