Sort filenames naturally with Qt

后端 未结 6 973
小蘑菇
小蘑菇 2020-12-03 20:34

I am reading a directories content using QDir::entryList(). The filenames within are structured like this:

index_randomNumber.png
6条回答
  •  隐瞒了意图╮
    2020-12-03 21:26

    If you want to use QCollator to sort entries from the list of entries returned by QDir::entryList, you can sort the result with std::sort():

    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    dir.setSorting(QDir::NoSort);  // will sort manually with std::sort
    
    auto entryList = dir.entryList();
    
    QCollator collator;
    collator.setNumericMode(true);
    
    std::sort(
        entryList.begin(),
        entryList.end(),
        [&collator](const QString &file1, const QString &file2)
        {
            return collator.compare(file1, file2) < 0;
        });
    

    According to The Badger's comment, QCollator can also be used directly as an argument to std::sort, replacing the lambda, so the call to std::sort becomes:

    std::sort(entryList.begin(), entryList.end(), collator);
    

提交回复
热议问题