Search code examples
qtpathinitializationdirqtreeview

How to initialize the starting path in Qt treeview?


I want to initialize the starting path in Qt treeview to the user home on Linux Ubuntu.

enter image description here

I tried this code but it does not work.

QString sPath = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx";
dirmodel = new QFileSystemModel(this);
dirmodel->setFilter(QDir::NoDotAndDotDot | QDir::AllDirs);
dirmodel->setRootPath(sPath);
ui->treeView->setModel(dirmodel);
  • I have tested the sPath :
    1. /home/<username>
    2. ${HOME}
    3. /home/casper/Music

No one works. =[

How to solve this?

Thank you for your help.


Solution

  • Once the model is loaded, I think you need to call setRootIndex on the tree widget:

    ui->treeView->setRootIndex(dirmodel->index("/home/casper"));
    

    Or for any home directory (also works on Windows, OSX, etc.):

    ui->treeView->setRootIndex(dirmodel->index(QDir::homePath()));