How to sort QList<QVariant> in Qt?

梦想与她 提交于 2019-12-04 23:19:18

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);
 }
albertTaberner

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

For QList sorting your can use qSort

If you like to use QVariant for sorting or similar it has some stumblestones. Depending what you like to do you may write your own operator overlays.

BUT it bears quite a bit of danger! Because you might have to compare non-compatible values

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;
        }
    }
}    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!