Search code examples
qtqt5.6

Getting all the files names from folder to a scroll area in QT


I am new to QT and I want to know how I can get all the file names from a folder to a scroll area and allow the users to click on it to do a function.


Solution

  • I think you should read some documentation to understand how Qt works.

    To get all files in directory, you can use entryInfoList() method of QDir. It is simple to use QListWidget to show this files.

    You can create function to get files something like

    QDir dir(path);
    for (const QFileInfo &file : dir.entryInfoList(QDir::Files))
    {
        QListWidgetItem *item = new QListWidgetItem(file.fileName());
        item->setData(Qt::UserRole, file.absolutePath()); // if you need absolute path of the file
        listWidget->addItem(item);
    }
    

    If you don't want to use absolute path then you can use just entryList() method.

    QDir dir(path);
    for (const QString &filename : dir.entryList(QDir::Files)
        listWidget->addItem(filename);
    

    And connect to itemClicked() signal of QListWidget to do something when the user has clicked the entry.