Search code examples
qtsortingqabstracttablemodelqsortfilterproxymodel

sorting currency formatted numbers in QAbstractTableModel


I have a QAbstractTableModel subclass that implements data() and some of the columns are ints and doubles. I am using QLocale::toCurrencyString() and QLocale::toString() to convert those numbers based on locale to add formatting characters such as '$' and ','. Since the result is a string, the columns are now sorting the values in string form and not int or double form.

I am using QSortFilterProxyModel to sort based on column. But it's just getting the data in string form, and sorting based on that. Maybe I'm not supposed to be formatting the ints and doubles in data()? I couldn't find another place to format those values. Does anyone know how to solve this problem?


Solution

  • You should make your QAbstractTableModel implementation return a string for Qt::DisplayRole, and the raw double for Qt::EditRole.

    Then call setSortRole(Qt::EditRole) on the QSortFilterProxyModel.

    This might not be the easiest way, but I believe it would be most in keeping with Qt's design philosophies.