问题
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