How to permanently sort a QStandardItemModel?
-
I have a program where I am trying to implement sorting on a qstandarditemmodel that is displayed in a table view. However, the method I am using doesn't seem to actually sort the model itself, but only the view. I need it to be able to sort the source model because I save the data to a .csv file using a delegate that passes the items from the model into an object of a class, and if the view is the only thing that is sorted it causes data loss due to the positions of the items in the view being changed but not in the model itself.
This is the code I use in the mainwidget constructor to connect the headerview clicked signal to a method that sorts the model:
currentStudentsModel = new QStandardItemModel(this); ui->currentTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->currentTableView->setModel(currentStudentsModel); ui->currentTableView->setItemDelegate(currentStudentsDelegate); currentTableHeader = ui->currentTableView->horizontalHeader(); connect(currentTableHeader, SIGNAL(sectionClicked(int)), this, SLOT(on_sectionClicked(int)));
Here is on_sectionClicked():
void mainWidget::on_sectionClicked(int index) { currentStudentsModel->sort(index,Qt::AscendingOrder); }
As I previously stated, this appears to only sort the items in the view as when I try to output all of the records stored in the model it has not changed from when they were initially entered. How do I get the model to be sorted itself and that order to be saved?
-
Use a QAbstractItemModel - that one allows you to take full control over the underlying data (you can store it in a QVector, for example - then sorting is very easy).
The disadvantage here is that to make the abstract model work you'll have to reimplement some more functions in your subclass.
-
Put a QSortFilterProxy model in-between. then save from the proxy instead of the main model.
P.S.
connect(currentTableHeader, SIGNAL(sectionClicked(int)), this, SLOT(on_sectionClicked(int)));
andvoid mainWidget::on_sectionClicked(int index)
are useless. this is the default behaviour of QTableView, you don't have to implement it manually