2016-06-15 96 views
0

我有一個QTableView的一些數據。數據有時會改變,然後我需要刷新TableView。刷新後,光標丟失位置。如果它在5位置(行),刷新超出tableview(或第一行)之後。我想讓它回到5,但它不起作用。QTableView和設置指針位置

我通過「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); 

回答

3

通過調用setModel,您更新模型,因此你的索引可能不再有效:

注:型號指標,應立即使用,然後丟棄。在調用模型 函數(更改模型結構或刪除項目)後,您不應依賴索引保持有效。如果 您需要保持模型索引隨着時間的推移使用QPersistentModelIndex。

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

+0

好了,我怎麼可以設置一個指向一個特定的位置。因爲通過QModelIndex index = ui-> tableView-> currentIndex(); int row = index.row();我知道最後一個活躍的位置。 – exo

+0

您可以使用'row()'值通過'index(...)'從模型中獲取一個新的'QModelIndex'並將其用於'setCurrentIndex()'。 –

+0

謝謝你的幫助。我仍然有問題。我做了這個構造'QPoint point(row,0);''index = ui-> tableView-> indexAt(point);''ui-> tableView-> setCurrentIndex(index);'。現在行被選中,但位置錯誤。始終保持在第一個可見的行。 – exo