c++qtqtreeviewqfilesystemmodel

ScrollTo a file in QTreeView with a QFileSystemModel on start-up


Last few hours I've been reading but not finding a good solution to what would seem a simple common problem. I have a QTreeView with a QFileSystemModel. I want to set the current index to the last file saved by the user and to scroll to that position. Because the qfilesystemmodel loads in an asynchronous way, if i immediately use the function scrollTo(mydesiredindex), like so:

Model = new QFileSystemModel;
Model->setRootPath(RootDirectory);
Model->setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
ui.RootView->setModel(Model);
ui.RootView->setCurrentIndex(Model->index(LastUsedPath));
ui.RootView->scrollTo(Model->index(LastUsedPath));

the qtreeview scrolls to the file's current location, but then adds more files before it, so that mydesiredindex is pushed out of view.

I've tried to get a signal that the model finished populating the tree view, but to no avail. the signals directoryLoaded(const QString &), and rowsInserted(const QModelIndex &, int, int)) send out signals before before the model finishes populating.

Thanks for anyone's help.


Solution

  • I believe it may be related to the ordering of your commands. I order it as follows

    self.tree.scrollTo(index)
    self.tree.expand(index)
    self.tree.setCurrentIndex(index)
    

    Or in your code

    ui.RootView->scrollTo(Model->index(LastUsedPath));
    ui.RootView->expand(Model->index(LastUsedPath));
    ui.RootView->setCurrentIndex(Model->index(LastUsedPath));
    

    Hope it helps.