26

I have the following datastructure.

QList<QVariant> fieldsList

How can I sort this list? This list contains strings. I want to sort the fieldList alphabetically?

vahancho
  • 20,808
  • 3
  • 47
  • 55
dexterous
  • 6,422
  • 12
  • 51
  • 99

3 Answers3

74

In Qt5, it seems qSort is deprecated. It's recommended to use:

#include <algorithm>
QList<QVariant> fieldsList;
std::sort(fieldsList.begin(), fieldsList.end());

Reference: site

Martin Delille
  • 11,360
  • 15
  • 65
  • 132
albertTaberner
  • 1,969
  • 1
  • 26
  • 35
  • 1
    Just a short note that apparently it is still valid in Qt4: [link](http://doc.qt.io/qt-4.8/qtalgorithms.html#qSort) – Cerno Apr 08 '16 at 14:02
29

I would do sorting in the following way:

 // Compare two variants.
 bool variantLessThan(const QVariant &v1, const QVariant &v2)
 {
     return v1.toString() < v2.toString();
 }

 int doComparison()
 {
     [..]
     QList<QVariant> fieldsList;

     // Add items to fieldsList.

     qSort(fieldsList.begin(), fieldsList.end(), variantLessThan);
 }

Update: in QT5 the qSort obsoleted. But it is still available to support old source codes. It is highly recommended to use std::sort instead of that in new codes.

SpongeBob
  • 383
  • 3
  • 16
vahancho
  • 20,808
  • 3
  • 47
  • 55
-3
int n;
int i;
for (n=0; n < fieldsList.count(); n++)
{
    for (i=n+1; i < fieldsList.count(); i++)
    {
        QString valorN=fieldsList.at(n).field();
        QString valorI=fieldsList.at(i).field();
        if (valorN.toUpper() > valorI.toUpper())
        {
            fieldsList.move(i, n);
            n=0;
        }
    }
}    
  • 1
    You should always avoid doing manual sorting unless you have a good reason for that. This is inefficient and makes the code unnecessarily more confusing. – Adriel Jr Jan 30 '19 at 18:55