Question

I am using QFileSystemModel with QTreeView to display the contents of root directory, now want to refresh the qtreeview whenever a drive is added or removed.

Tried with a refresh push button to achieve this with a slot, to delete the model and setting it to QTreeView again. but problem here is, its not expanding the column width to its contents after setting the model to the view on second time.

is there any best solution to achieve this. here is a code bit...

QTreeView fileExplorerTreeView = new QTreeView();
fileExplorerTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
fileExplorerTreeView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);

void loadFileExplorer()
{
    if(fileSystemModel)
    {
        delete fileSystemModel;
        fileSystemModel = 0;
     }

    fileSystemModel = new QFileSystemModel;
    fileSystemModel->setRootPath("");


    fileExplorerTreeView->setModel(fileSystemModel);

    QHeaderView* hHeader = fileExplorerTreeView->header();
    hHeader->hideSection(1);
    hHeader->hideSection(2);
    hHeader->hideSection(3);

    fileExplorerTreeView->resizeColumnToContents(0);
    fileExplorerTreeView->header()->setStretchLastSection(false);
}
Was it helpful?

Solution

The problem is that the model is not watching for fs changes, and not updating. And you want it to control at the higher level.

So, if you set your rootpath to my computer, it should work:

QString rPath = fileSystemModel->myComputer().toString(); 
fileSystemModel->setRootPath(rPath);

Here was a similar problem (changing filters didnt update model) solved this way.

Also, you should not have to resize the table with each change.

Just change the resize mode with:

void QHeaderView::setSectionResizeMode(int logicalIndex, ResizeMode mode)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top