View Full Version : Display a string in a QTableView but sort using an associated integer value

5th June 2010, 21:29
Hi everyone,

I'm using a QAbstractTableModel and a QSortFilterProxyModel with a tableview like this :

MyTableModel *model = new MyTableModel(searcher);
MyQSortFilterProxyModel *proxyModel = new MyQSortFilterProxyModel();

When i click on a column header it is sorted but it's using the default comparison operator of the types used in the model.
I have a field representing an age in number of days but i display it in the tableview like "2 years".
I'm trying to get the proxy model to sort this column using the integer value and the tableview to display it using its string representation.

What would be the easiest way to obtain this behavior ?

Thank you.

5th June 2010, 22:34
Well i eventually managed to do it using a custom role in the tablemodel, subclassing the proxymodel and re-implementing the lessThan method.
For people interested this is my lessThan methode in the proxymodel :

bool MyQSortFilterProxyModel::lessThan(const QModelIndex &left,
const QModelIndex &right) const
QVariant leftData = sourceModel()->data(left);
QVariant rightData = sourceModel()->data(right);

if(left.data(Qt::UserRole).type() == QVariant::Double)
return (left.data(Qt::UserRole).toDouble() < right.data(Qt::UserRole).toDouble());
else if(leftData.type() == QVariant::String)
return (leftData.toString() < rightData.toString());