QT Windows 资源管理器的排序规则

如果你使用QTableView装载数据,那么一定会遇到点击表头进行排序的需求。如果不进行任何自定义排序,那么QT的默认的排序(首字符的编码进行排序)可能并不符合用户的预期。如果我们的排序规则跟Windows资源管理器保持一致,那么用户应该不会再对排序有其他异议了。

以下是使用QT的 QCollator 进行自然排序的示例代码,这个函数可以对字符串列表进行类似Windows资源管理器的自然排序,它能正确处理字符串中的数字部分,比如"file2"会排在"file10"之前。

cpp 复制代码
#include <QCoreApplication>
#include <QRegularExpression>
#include <QCollator>
#include <QDebug>

QStringList sortStringListNatural(const QStringList &strList, bool bAscending)
{
    // 创建排序器,使用当前系统区域设置
    QCollator qCollator;
    qCollator.setNumericMode(true);  // 启用数字模式,将数字作为数值而非字符串比较
    qCollator.setCaseSensitivity(Qt::CaseInsensitive);  // 不区分大小写

    // 创建结果列表的副本
    QStringList strResult = strList;

    // 使用Lambda表达式进行排序比较
    if (bAscending) {
        // 升序排序
        std::sort(strResult.begin(), strResult.end(),
            [&qCollator](const QString &str1, const QString &str2) {
                return qCollator.compare(str1, str2) < 0;
            });
    } else {
        // 降序排序
        std::sort(strResult.begin(), strResult.end(),
            [&qCollator](const QString &str1, const QString &str2) {
                return qCollator.compare(str1, str2) > 0;
            });
    }

    return strResult;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QStringList names = {
            "file1.txt",
            "file10.txt",
            "file2.txt",
            "File20.TXT",
            "file3.txt",
            "readme",
            "文件100.dat",
            "文件20.dat"
        };
    QStringList result = sortStringListNatural(names, true);
    qDebug() << "result=" << result;

    return a.exec();
}

输出结果:

bash 复制代码
result= ("file1.txt", "file2.txt", "file3.txt", "file10.txt", "File20.TXT", "readme", "文件20.dat", "文件100.dat")
相关推荐
xcyxiner2 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner2 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner3 天前
DicomViewer (添加模型类)3
qt
xcyxiner4 天前
DicomViewer (目录调整) 2
qt
xcyxiner4 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
qq_369224335 天前
Windows全系通用!ntdll.dll文件丢失、报错、闪退问题的完整排查与修复教程
windows·dll·dll修复·dll丢失·dll错误
桥田智能6 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G6 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
阿米亚波6 天前
【Windows】QEMU 启动 openEuler aarch64/arm64 架构系统 + 离线软件源
linux·windows·经验分享·笔记·架构·arm
森G6 天前
77、线程池原理和实现------服务器源码解析----云视频服务项目
服务器·c++·qt