Let’s say I have a QTableView with a corresponding model. This view shows numbers only, and I want different number formats for different columns.
Some examples:
- In the price column I want two decimals and a comma as separator.
- In the length column I don’t want any decimals but I still want the
comma separator. - In the duration column I want the same format as the price column but
red color if the value is negative.
Now I could do this in the model’s data function. Qt.DisplayRole handles the number formatting, and Qt.ForegroundRole can handle the coloring. While the coloring works as intended, doing the number formatting this way breaks sorting.
Is there a way more straight forward way to achieve this? I tried Googling around to see what I could find, but good examples of what I’m after eludes me.
If you are using
QStandardItemModelas your model, you can set thesortRoleto use, say,Qt::EditRoleinstead ofQt::DisplayRole.If you are using something like
QAbstractItemModel, you can override thesortmethod and do something similar, i.e. use theQt::EditRolevalue. You could also wrap aQSortFilterProxyModelaround your model and override thelessThanmethod.