简体   繁体   中英

qt - 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?

QStandardItemModel does not implements sort.

From Qt documentation:

void QAbstractItemModel::sort(int column, Qt::SortOrder order = Qt::AscendingOrder)

Sorts the model by column in the given order. The base class implementation does nothing.


You need to sort through QSortFilterProxyModel

currentStudentsProxyModel = new QSortFilterProxyModel;
currentStudentsModel->setSourceModel( currentStudentsProxyModel );
currentStudentsProxyModel->sort( 0, Qt::AscendingOrder );

void mainWidget::on_sectionClicked(int index)
{
    currentStudentsProxyModel->sort(index,Qt::AscendingOrder);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM