PDA

View Full Version : Applying two FileFilterProxyModel on one QFileSystemModel



high_flyer
17th June 2020, 15:11
Hi,

I thought this will be a no-brainer, but it became a problem I could no solve so far.
Interestingly enough, similar cases I could find online use two QFileSystemModels which I think just can't be the right solution.

The problem:
I am making a sort of file explorer, that has one view of the directories, and another view shows the files in the selected directory.
So the idea was to have one QFileSystemModel, and apply two FileFilterProxyModel's on it, one to show only folders, one to show only files (for selected folder, no sub folders)

The folders view work fine.
The files view work fine, for the first (root) folder, when the UI shows up.
After that, any selection on the folder view, getting the index from the folder view and transforming it back to the source model index works fine, but when I try to translate the index from the source to the file filter model it always returns an invalid index, except for the first time , which means the file view always shows only the root folder content.

Here is my code:

The models initialization:


void MainWindow::initFilesystemModel()
{
m_pFileSystemModel = new QFileSystemModel(this);
m_pFileSystemModel->setFilter(QDir::AllDirs|QDir::NoDotAndDotDot|QDir: :Hidden|QDir::Drives|QDir::Files);
m_pFileSystemModel->setRootPath(QDir::rootPath());

m_pOnlyFoldersFilterModel = new FileFilterProxyModel(ui->pFolderTreeView);
m_pOnlyFoldersFilterModel->setSourceModel(m_pFileSystemModel);

QSortFilterProxyModel* onlyFilesModel = new OnlyFilesFileterModel(ui->pDetailViewWidget);
onlyFilesModel->setSourceModel(m_pFileSystemModel);

ui->pFolderTreeView->setModel(m_pOnlyFoldersFilterModel);
ui->pDetailViewWidget->setModel(onlyFilesModel);

connect(ui->pFolderTreeView, &QTreeView::pressed, this , &MainWindow::onFolderSelected);

}


And the reaction to selecting a folder:
Note the comments in the code


void MainWindow::onFolderSelected(const QModelIndex &index)
{
std::cout<<"index "<<index.row()<<" "<<index.column()<<std::endl;
QModelIndex sourceIndex = m_pOnlyFoldersFilterModel->mapToSource(index); //sourceIndex is valid and correct
std::cout<<"source index "<<sourceIndex.row()<<" "<<sourceIndex.column()<<std::endl;
QModelIndex rootIndex = dynamic_cast<QSortFilterProxyModel*>(ui->pDetailViewWidget->model())->mapFromSource(sourceIndex); //Always invalid index
std::cout<<"root index:"<<rootIndex.row()<<" "<<rootIndex.column()<<std::endl;
ui->pDetailViewWidget->setRootIndex(rootIndex);
}


I must be missing something, or overlooking something, would very much appreciate any pointers, and things to try.
Thanks!