Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
QTableView - formatting data and the EditRole and DisplayRole
IceBoot last edited by
I am writing an application to display some data (strings, numbers, etc.) in a QTableView using a QStandardItemModel. I have enabled sorting such that clicking on the column name sorts the content of the QTableView according to the data in that column. Now to my problem; if I insert the data as strings and format the numbers f.ex. with 3 decimals it all looks nice but the sorting fails (sorts the strings but thats not what I want). The other way is to insert the data as numbers(QVariant) which gives correct sorting but then the numbers have different number of decimals etc.
Is there a way to insert the data into the model once (numbers as numbers, strings as strings) and then make the sorting use these values but have a different format for viewing the data? I have not understood the use of DisplayRole versus EditRole - can this be used in any way? Some hints would be greatly appreciated. Here's som snippets of my code:
datalogViewModel = new QStandardItemModel();
datalogViewModel ->setHorizontalHeaderItem(value, new QStandardItem(QString(tr("Value"))));
int valueColNo = 1;
for(....) // value is set here (double)
QStandardItem* item = new QStandardItem();
item->setData(QVariant(value), Qt::EditRole); // For the sorting to become correct
//item->setData(QString::number(value, 'f', 3), Qt::DisplayRole); // For display, but this does not work...
datalogViewModel->setItem(rowNo, valueColNo, item);
Hi and welcome to devnet,
DisplayRole is what you show to the user and EditRole is what you will load in the editor, both can be different.
The easiest would be to store everything in only one type and the use e.g. a QStyledItemDelegate to show the data like you want.
Hope it helps