Sort filenames naturally with Qt(使用 Qt 自然地对文件名进行排序)
问题描述
我正在使用 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?
推荐答案
如果你想使用 QCollator 对 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的评论,QCollator也可以直接使用作为 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 自然地对文件名进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Qt 自然地对文件名进行排序
				
        
 
            
        基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				