c++ - QTableView并设置指针位置

标签 c++ qt qtableview

我有一个带有一些数据的 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

关于c++ - QTableView并设置指针位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827363/

相关文章:

c++ - 字符串作为 C++ 中宏的参数

c++ - 令人困惑的继承示例。构造函数被重写,但函数没有。为什么?

c++ - static_cast 会影响简单类型 float 的 Boost 吗?

c++ - QTabWidget - 如何分别编辑每个小部件?

c++ - QLibrary 解析返回 false

python - PyQt5 中的 QTableView clicked.connect() 键盘滚动等效

c++ - 带有行中图标的 QTableView

c++ - 在鼠标 Hook 中,滚轮增量始终为 0

Qt 样式表 - 同一类型小部件的不同样式

python - 编辑 QTableView 单元格值