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?
I would replace this line:
with this as per the official custom sort/filter model example:
The advantage is that it will handle the string correctly for the user's locale as per documentation.
However, I would personally just use the sort order enumeration for this task as per documentation:
Ascending...
Descending...
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.