How to iterate all sub-folders of a directory?

  • Hi, I am showing file same in tree view using QDirModel. The user can select a given folder and my application need to traverse all its subfolders (only one level). I haven't been able to figure out how but here is where I am stuck.

    @// I can get the index of the current selected folder
    QModelIndex index = ui->treeView->currentIndex();@

    Now else where I see I could use something like this:

    @ QDirIterator it("/etc", QDirIterator::Subdirectories);
    while (it.hasNext()) {
    qDebug() <<;

     // /etc/.
     // /etc/..
     // /etc/X11
     // /etc/X11/fs
     // ...


    The problem is how to get the currently selected for as QDir object from tree and list view and feed it to the 2nd block of code?

    Initially I used QFileSystemModel which I know is recommended now instead of QDir but it proved more complicated. I would prefer solution with QFileSystemModel but QDirModel is also acceptable.

  • Lifetime Qt Champion


    Do you mean "QFileSystemModel::filePath": ?

  • You can get the directory from the special roles the QFileSystemModel supplies for you:
    enum Roles { FileIconRole, FilePathRole, FileNameRole, FilePermissions }

    Sound to me like the FilePathRole provides a complete path. Using QFileInfo, you can easily figure out if the current item is a file or a dir, and what the path to use is.

  • Sorry guys, I was not thinking right. I figured it all out. Here is what I and I did use QFileSystemModel.

    @void MainWindow::on_actionExport_files_triggered()
    QModelIndex index = ui->treeView->currentIndex();

    QString rootDir = dirModel->filePath( selectedIndex );
    QDirIterator iter( rootDir, QDir::Dirs | QDir::NoDotAndDotDot);
    while(iter.hasNext() )
        qDebug() <<;


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.