Qt QItemSelection不会更改QItemSelectionModel::currentIndex()

Qt QItemSelection不会更改QItemSelectionModel::currentIndex(),qt,Qt,我以编程方式在QTableView中创建一个选择: QItemSelectionModel * selectionModel = ui->tableView->selectionModel(); selectionModel->clear(); // Select the whole row QModelIndex topLeft = tableModel->index(row, 0, QModelIndex()); QModelIndex topRight = tab

我以编程方式在
QTableView
中创建一个选择:

QItemSelectionModel * selectionModel = ui->tableView->selectionModel();
selectionModel->clear();

// Select the whole row
QModelIndex topLeft = tableModel->index(row, 0, QModelIndex());
QModelIndex topRight = tableModel->index(row, tableModel->columnCount()-1, QModelIndex());
QItemSelection selection(topLeft, topRight);
selectionModel->select(selection, QItemSelectionModel::Select);
然后我有一个
按钮
,单击该按钮可获取当前选定的索引:

QModelIndex currentIndex = ui->tableView->selectionModel()->currentIndex();
if (currentIndex.isValid())
{
  // Pop open a dialogue
}
当我使用第一块代码进行选择时,表中的行将高亮显示。但是,当我单击
按钮时,对话框不会打开,这表明
currentIndex()
返回的
QModelIndex
无效。为什么会这样


我可以先用鼠标点击已经高亮显示的表格行,弹出对话。则当前索引有效。

当前索引与所选索引不同。不要混淆这两个概念。当前索引只能有一个,但一次可以有多个选定索引。您可以改为检查所选索引:

QModelIndexList indexes = ui->tableView->selectionModel()->selectedIndexes();
if (indexes.size() > 0) {
  // Pop open a dialogue
}