How to sort QList<QVariant> in Qt?

偶尔善良 提交于 2019-12-10 00:57:15

问题


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?


回答1:


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



回答2:


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




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/21578577/how-to-sort-qlistqvariant-in-qt

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