Reputation: 17223
I am trying to sort Items in a specific column of QStandardItemModel
alphabetically.
For this I am using a class that derives from QSortFilterProxyModel
and I am reimplementing the lessThan
method as such
bool MyProxy::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
QVariant leftData = sourceModel()->data(left);
QVariant rightData = sourceModel()->data(right);
if( left.column() == 1)
{
return leftData.toString() < rightData.toString();
}
return false;
}
Here is how I am attaching the model to the proxy model
MyStandardItemModel=new QStandardItemModel();
MyProxy= new MyProxy();
MyProxy->setSourceModel(pModelContacts);
ui.ContactView->setModel(MyProxy);
After adding items to the model here is what I do to sort
MyProxy->sort(1);
However the column does not show up sorted. Any suggestions?
Upvotes: 2
Views: 3259
Reputation: 53173
I would replace this line:
return leftData.toString() < rightData.toString();
with this as per the official custom sort/filter model example:
return QString::localeAwareCompare(leftData.toString(), leftData.rightString()) < 0;
The advantage is that it will handle the string correctly for the user's locale as per documentation.
int QString::localeAwareCompare(const QString & other) const
This function overloads localeAwareCompare().
Compares this string with the other string and returns an integer less than, equal to, or greater than zero if this string is less than, equal to, or greater than the other string.
The comparison is performed in a locale- and also platform-dependent manner. Use this function to present sorted lists of strings to the user.
Same as localeAwareCompare(*this, other).
However, I would personally just use the sort order enumeration for this task as per documentation:
enum Qt::SortOrder
Ascending...
Qt::AscendingOrder 0
The items are sorted ascending e.g. starts with 'AAA' ends with 'ZZZ' in Latin-1 locales
Descending...
Qt::DescendingOrder 1
The items are sorted descending e.g. starts with 'ZZZ' ends with 'AAA' in Latin-1 locales
So, this line would be enough without the lessThan method override because the default sorting order is ascending and that seems to be the case what your code is trying to reimplement.
MyProxy->sort(1);
Upvotes: 1