Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Natural sort using QCollator



  • I have been looking for any basic example using QCollator to sort naturally a QStringList variable full of filenames like this:

    image1.jpg
    image10.jpg
    image11.jpg
    image2.jpg
    image3.jpg
    

    The result I am expecting is this:

    image1.jpg
    image2.jpg
    image3.jpg
    image10.jpg
    image11.jpg
    

    I appreciate any suggestion. Thanks.


  • Moderators

    QStringList stuff;
    stuff << "image1.jpg"
          << "image10.jpg"
          << "image11.jpg"
          << "image2.jpg"
          << "image3.jpg";
    
    QCollator coll;
    coll.setNumericMode(true);
    
    std::sort(stuff.begin(), stuff.end(), [&](const QString& s1, const QString& s2){ return coll.compare(s1, s2) < 0; });
    

Log in to reply