QTableView并设置指针位置

QTableView and set pointer position

我有一个带有一些数据的 QTableView。数据有时会发生变化,然后我需要刷新 TableView。刷新后,光标失去位置。如果它在 5 个位置(行),刷新后会超出 tableview(或在第一行)。我想让它回到 5,但它不起作用。

我通过“index = ui->tableView->currentIndex()”保存了最后一个位置并通过“ui->tableView->setCurrentIndex(index)”取回了它

怎么了?

//save last cursor(row) position
QModelIndex index = ui->tableView->currentIndex();

//create basic model with my data
myModel = new MyModel();

//insert my model to sortfilterproxymodel and then sort it
QSortFilterProxyModel *sort_filter = new QSortFilterProxyModel(this);
sort_filter->setSourceModel(myModel);
sort_filter->setSortCaseSensitivity(Qt::CaseInsensitive);
sort_filter->sort(0, Qt::AscendingOrder);       //sort by name
sort_filter->sort(5, Qt::DescendingOrder);      //sort by surename

//insert my data to tableview
ui->tableView->setModel(sort_filter);
ui->tableView->hideColumn(5);

//return it back to its original position
ui->tableView->setCurrentIndex(index);

通过调用 setModel,您更新了模型,因此您的索引可能不再有效:

Note: Model indexes should be used immediately and then discarded. You should not rely on indexes to remain valid after calling model functions that change the structure of the model or delete items. If you need to keep a model index over time use a QPersistentModelIndex.

http://doc.qt.io/qt-5/qmodelindex.html#details