QDir and nameFilters



  • Hi all,

    I want to retrieve the entries of a directory containing files and folders and I want only those files matching a particular pattern. But when I use QDir::setNameFilters() it also tries to match directory names. How can the nameFilters be applied to files only and not to directories?

    Cheers,
    Stephan



  • @DuBu said in QDir and nameFilters:

    QDir::setNameFilters

    You cannot separate these two at the QDir level. (Nor, for the record, can one do so at the underlying Windows/Linux OS call level, so you're not "losing" anything.

    You either have to make separate calls, or you need to do the name filtering yourself on the returned values. See, for example, https://stackoverflow.com/questions/13051418/set-name-filters-only-on-files-not-on-dirs



  • Hi @DuBu ,
    I believe you can simply also set a Filter via setFilter

    This is the Filter for only files.

    QDir dir;
    dir.setFilter(QDir::Files);
    


  • @JonB Ok, too bad. I'll have a look at it. Thanks for the really quick answer!



  • @J.Hilk The filter is set to QDir::AllEntries already.



  • @DuBu correct AllEntries = Dirs | Files | Drives, and you only want file names, right?
    So change it to QDir::Files

    If you want filenames filtered and all folders, than I would suggest 2 QDirs with different filters that you combine than.



  • @J.Hilk said in QDir and nameFilters:

    If you want filenames filtered and all folders, than I would suggest 2 QDirs with different filters that you combine than.

    That is what he has said he wants. Hence he can either make two separate calls, or one call with no name filtering and do the name filtering himself.



  • So, here's my solution:

    foreach (const QFileInfo & fileInfo, _dir.entryInfoList(QDir::Dirs)) {
      _entryInfos.append(fileInfo);
    }
    foreach (const QFileInfo & fileInfo, _dir.entryInfoList(_nameFilters, QDir::Files)) {
      _entryInfos.append(fileInfo);
    }
    


  • @DuBu said in QDir and nameFilters:

    So, here's my solution:

    foreach (const QFileInfo & fileInfo, _dir.entryInfoList(QDir::Dirs)) {
      _entryInfos.append(fileInfo);
    }
    foreach (const QFileInfo & fileInfo, _dir.entryInfoList(_nameFilters, QDir::Files)) {
      _entryInfos.append(fileInfo);
    }
    

    Seems promising, just one more thing, foreach is technically discarded, I would go with the "new" for(x : y) style;

    for (const QFileInfo & fileInfo : _dir.entryInfoList(QDir::Dirs)) {
      _entryInfos.append(fileInfo);
    }
    for (const QFileInfo & fileInfo : _dir.entryInfoList(_nameFilters, QDir::Files)) {
      _entryInfos.append(fileInfo);
    }
    

Log in to reply
 

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