c++linuxqtqtreeviewqfilesystemmodel

How to set a starting point directory to a QTreeView?


Lets say I have this folders in my system:

/home/rob/musics/...
/home/rob/texts/...
/home/rob/images/...

I'm trying to create a qtreeview(I don't know if this is the most appropriate widget to that) to show only the folders/subfolders and files inside /rob/ directory. But the problem is the way I'm doing it shows me all directories inside the root directory.

What I want to see(files and access to the subfolders):

/musics/...
/texts/...
/images/...

What I'm getting:

/home/
/lib/
/root/
/usr/
/...

I don't want that! How can I set a starting point to this file system? Here what I tried:

//  fsmodel is a QFileSystemModel
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),  ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    const QString rootPath = "/home/rob/";

    fsModel = new QFileSystemModel(this);
    fsModel->setRootPath(rootPath);

    ui->treeView->setRootIndex(fsModel->index(rootPath));
    ui->treeView->setModel(fsModel);
}

I'm using linux.


Solution

  • If you execute your code you should get the following warning message:

    QAbstractItemView::setRootIndex failed : index must be from the currently set model
    QAbstractItemView::setRootIndex failed : index must be from the currently set model
    

    And it is obvious, QTreeView does not have a model yet but you are passing it a rootIndex of a model that it does not know.

    The solution is to first set the model and then the rootIndex:

    ui->treeView->setModel(fsModel);
    ui->treeView->setRootIndex(fsModel->index(rootPath));