Harsh J

Memoirs of a QWERTY Keyboard

Archive for the ‘QMap’ tag

Sorting entries in a QStringList Case-insensitively

4 comments

This post is simply a snippet-post for the users of Nokia’s Qt C++ cross-platform toolkit.

While writing some C++ code (after 2 long years since I last wrote them for academic reasons), I had this simple issue of sorting a QStringList in a case-insensitive manner. Normally, there exists a QStringList::sort() function that does the sorting of the strings stored in it in a case-sensitive manner, and is very fast at it. But Qt does not provide a way to perform the sort in a non case-sensitive manner, although it has hints on how to in the class’ documentation.

Being mostly a PyQt/PySide user who uses inbuilt Python lists to do all list-work, here’s how its apparently done in Qt/C++, using a QtCore class called QMap:

#include <QtCore/QStringList>
#include <QtCore/QMap>

void sortNonCaseSensitive( QStringList &sList ) {
    ///  Sorts the passed sList non-case-sensitively.
    ///  (Preserves the cases! Just doesn't use them
    ///  while sorting.)
    QMap<QString, QString> strMap;
    foreach ( QString str, sList ) {
        strMap.insert( str.toLower(), str );
    }
    sList = strMap.values();
}

That’s it.

Written by Harsh

October 24th, 2009 at 10:54 pm