Hi,
I have a QTableView with some columns, one column is with numbers only. If I sorting this column, it's 1, 11, 12 ... 2, 21, 22 ... but I need 1, 2, 3 ... 10, 11, 12 ...
How can I do this?
Thx!
Chris
Printable View
Hi,
I have a QTableView with some columns, one column is with numbers only. If I sorting this column, it's 1, 11, 12 ... 2, 21, 22 ... but I need 1, 2, 3 ... 10, 11, 12 ...
How can I do this?
Thx!
Chris
Hi Chris, you need to make sure your database column is a number type, then it would sort correctly. It looks to me like it's a character or varchar type and that's why it is sorting like that.
Ok, but how can I do that?
What is the model underlying the view? Is it a QStandardItemModel, QSqlTableModel or something else?
Are doing this from a database? If so, how are you defining the column spec when you create the table?
Code:
... QList<QStandardItem *> column1, column2, column3, column4, column5; foreach (...) { ... } model->appendColumn(column1); model->appendColumn(column2); ... model->setHeaderData(0, Qt::Horizontal, tr("Column1")); model->setHeaderData(1, Qt::Horizontal, tr("Column2")); ... ui->tableView->setModel(model);
column5 data are numbers only! "79962", "35776", "140480", "120384" ... but all QStrings!
Well, that is the problem then. Even if strings contain only numbers, they will still sort order as strings, like you are seeing.
What happens if you load column5 like:
column5.append(new QStandardItem(1234)); ?
...this doesn't work unfortunately, the constructor allows no numbers!
Code:
I try to subclass QStandardItem, I think, this is the solution!
Code:
public: NumberItem(const int number); private: int value; public: int type() const; }; value = number; } int NumberItem::type() const { } return new NumberItem(*this); } }
than I append this to the model:
Code:
column5.append(new NumberItem(12345));
It work's, the numbers are in the column 5 of tableView, but all number cells are checkable and disabled!? I don't know, why! setCheckable(false) and setEnabled(true) doesn't work!
So create the item with the default constructor and then use QStandardItem::setData() to set a QVariant of type QVariant::Int (or Uint, LongLong etc.) as the data for the Qt::DisplayRole. Alternatively, set the integer data on the EditRole and use setSortRole on the model to set the sort role to the EditRole.
Ok, this works!
Code:
column5.append(item);
How can I do this? Have you a code snippet for me?
If setting the Qt::DisplayRole is working then just use that. However:
and, elsewhere:Code:
column5.append(item);
This makes all the columns in the model sort on the edit role.Code:
model->setSortRole(Qt::EditRole);
Ok, big thanks for your help!