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")
相关推荐
.m1 小时前
讯飞输入法3.0.1742功能简介
windows
她叫我大水龙1 小时前
Qt中的多线程
c++·qt
救救孩子把3 小时前
在 Windows上用WSL和VSCode进行Linux开发环境配置
linux·windows·vscode·wsl
love530love9 小时前
《Anaconda 精简路径治理》系列 · 番外篇Conda 虚拟环境路径结构方案全解——六种路径布局对比、优劣与治理建议
运维·人工智能·windows·python·conda
老马啸西风12 小时前
windows wsl2-05-docker 安装笔记
运维·windows·笔记·docker·容器·k8s
chilavert31813 小时前
技术演进中的开发沉思-40 MFC系列:多线程协作
c++·windows·mfc
long_mingyue17 小时前
网鼎杯2020青龙组notes复现
linux·服务器·windows
蜡笔小欣丫18 小时前
USB导出功能(QT)
开发语言·qt
真的想上岸啊18 小时前
学习C++、QT---27(QT中实现记事本项目实现行列显示、优化保存文件的功能的讲解)
c++·qt·学习