Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort QList<QVariant> in Qt?

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?

like image 428
dexterous Avatar asked Feb 05 '14 13:02

dexterous


2 Answers

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

like image 104
albertTaberner Avatar answered Nov 08 '22 14:11

albertTaberner


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.

like image 27
vahancho Avatar answered Nov 08 '22 14:11

vahancho