ScrollTo启动时使用QFileSystemModel滚动到QTreeView中的文件

问题描述 投票:3回答:1

最近几个小时,我一直在阅读,但是没有找到看似简单的常见问题的好的解决方案。我有一个带有QFileSystemModel的QTreeView。我想将当前索引设置为用户保存的最后一个文件,并滚动到该位置。因为qfilesystemmodel以异步方式加载,所以如果我立即使用函数scrollTo(mydesiredindex),如下所示:

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));

qtreeview滚动到文件的当前位置,但是在其之前添加了更多文件,因此mydesiredindex被推出了视图。

我试图获得一个信号,表明模型已完成填充树视图,但无济于事。在模型完成填充之前,信号directoryLoaded(const QString&)和rowsInserted(const QModelIndex&,int,int))发出信号。

感谢任何人的帮助。

c++ qt qtreeview qfilesystemmodel
1个回答
1
投票

我相信这可能与您命令的顺序有关。我如下订购

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

或在您的代码中

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

希望有帮助。


0
投票

这是由于QFileSystemModel工作的异步方式,而Qt中似乎从未修复的错误:https://bugreports.qt.io/browse/QTBUG-9326

您可以在调用QApplication::sendPostedEvents()之前立即执行scrollTo()来解决此问题,但是必须在连接到directoryLoaded信号的函数中调用它们:

MyFileBrowser::MyFileBrowser(QWidget *parent) : QWidget(parent), ui(new Ui::MyFileBrowser) {
  //...
  connect(model, SIGNAL(directoryLoaded(QString)), this, SLOT(dirLoaded(QString)));
  QModelIndex folderIndex = model->index("path/to/dir");
  files->setCurrentIndex(folderIndex);
  files->expand(folderIndex);
}

void WFileBrowser::dirLoaded(QString dir) {
    if (dir == model->filePath(files->currentIndex())) {
        QApplication::sendPostedEvents(); // booyah!!
        files->scrollTo(files->currentIndex(), QAbstractItemView::PositionAtTop);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.