Qt - QFileSystemModel如何获取文件夹中的文件(Noob)

use*_*754 1 c++ qt

我有以下代码列出listView中的文件:

fileModel = new QFileSystemModel(this);
ui->listView->setModel(fileModel);
ui->listView->setRootIndex(fileModel->setRootPath(filePath));
Run Code Online (Sandbox Code Playgroud)

我想获取路径中文件的列表/映射.如何才能做到这一点?

Mur*_*ker 5

以下代码段将执行您想要的操作:

QList<QString> path_list;
QModelIndex parentIndex = fileModel->index(filePath);
int numRows = fileModel->rowCount(parentIndex);

for (int row = 0; row < numRows; ++row) {
    QModelIndex childIndex = fileModel->index(row, 0, parentIndex);
    QString path = fileModel->data(childIndex).toString();
    path_list.append(path);
}
Run Code Online (Sandbox Code Playgroud)

有一件事你不应该忘记.从文档:

与QDirModel(已废弃)不同,QFileSystemModel使用单独的线程来填充自身,因此在查询文件系统时不会导致主线程挂起.对模型填充目录之前,对rowCount()的调用将返回0.

因此,您必须等到directoryLoaded(const QString & path)在启动模型后从QFileSystemModel 接收到信号,然后填写列表.

  • 您可以在我的答案中显示的循环中使用`QFileInfo(filePath +"\\"+ path).isDir()`.如果当前的`path`是目录,则返回true. (2认同)