简体   繁体   中英

Qt - QFileSystemModel How to Get Files in Folder (Noob)

I have following Code to list the files in the listView:

fileModel = new QFileSystemModel(this);
ui->listView->setModel(fileModel);
ui->listView->setRootIndex(fileModel->setRootPath(filePath));

I would like to get a list/Map to the files in a Path. how can this be done?

The following snippet will do what you want :

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

There is one thing that you should not forget. From the documentation :

Unlike QDirModel(obsolete), QFileSystemModel uses a separate thread to populate itself so it will not cause the main thread to hang as the file system is being queried. Calls to rowCount() will return 0 until the model populates a directory.

Hence, you have to wait until you receive directoryLoaded(const QString & path) signal from QFileSystemModel after you initiate the model, then fill your list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM