問題描述
我正在使用 QDir::entryList()
讀取目錄內容.里面的文件名結構如下:
I am reading a directories content using QDir::entryList()
. The filenames within are structured like this:
index_randomNumber.png
我需要按 index
對它們進行排序,Windows 資源管理器對文件進行排序的方式,以便我獲得
I need them sorted by index
, the way the Windows Explorer would sort the files so that I get
0_0815.png
1_4711.png
2_2063.png
...
而不是按 QDir::Name
排序給我的:
instead of what the sorting by QDir::Name
gives me:
0_0815.png
10000_6661.png
10001_7401.png
...
Qt 中是否有內置的方法來實現這一點,如果沒有,在什么地方實現它?
Is there a built-in way in Qt to achieve this and if not, what's the right place to implement it?
推薦答案
如果你想使用 QCollat??or
對 QDir::entryList
,你可以用 std::sort()
:
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(),
[&](const QString &file1, const QString &file2)
{
return collator.compare(file1, file2) < 0;
});
根據The Badger的評論,QCollat??or
也可以直接使用作為 std::sort
的參數,替換 lambda,因此對 std::sort
的調用變為:
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);
這篇關于使用 Qt 自然地對文件名進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!