You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt 6.6.1中QTableView代码恢复选中行呈灰色而非蓝色的问题

Qt 6.6.1表格选中状态恢复后显示灰色的原因及解决办法

问题原因

Windows 10下Qt表格的蓝色高亮对应既是选中项又是当前项(Current Item)的行;灰色高亮则是仅为选中项但非当前项的行。手动点击行时,Qt会同时将该行设为选中项和当前项,所以显示蓝色;而恢复时仅调用setCurrentIndex(或仅设置选中项),会导致两者状态不匹配,从而显示灰色。

另外,setCurrentIndex默认不会自动将该行加入选中集合(除非表格的选择行为和模式配置特殊),这也是单独调用它无效的核心原因。

解决办法

需要同时保存并恢复选中行集合和当前行索引两个状态,步骤如下:

1. 保存选中状态

// 保存选中的行索引
QList<int> savedSelectedRows;
const QModelIndexList selectedIndexes = ui->tableView->selectionModel()->selectedRows();
for (const QModelIndex& idx : selectedIndexes) {
    savedSelectedRows.append(idx.row());
}

// 保存当前行索引
int savedCurrentRow = ui->tableView->currentIndex().row();

2. 恢复选中状态

// 先清除原有选中状态
ui->tableView->selectionModel()->clearSelection();

// 恢复选中行
QItemSelection selection;
for (int row : savedSelectedRows) {
    QModelIndex idx = ui->tableView->model()->index(row, 0);
    selection.select(idx, idx); // 选中整行(需确保SelectionBehavior为SelectRows)
}
ui->tableView->selectionModel()->select(selection, QItemSelectionModel::Select);

// 恢复当前行(触发蓝色高亮)
if (savedCurrentRow >= 0 && savedCurrentRow < ui->tableView->model()->rowCount()) {
    QModelIndex currentIdx = ui->tableView->model()->index(savedCurrentRow, 0);
    ui->tableView->setCurrentIndex(currentIdx);
}

3. 确认表格选择配置

确保表格的选择行为和模式正确,避免状态不生效:

// 设置选中整行
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
// 根据需求设置选择模式,比如单选或多选
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); // 单选示例

内容的提问来源于stack exchange,提问作者Fabio says Reinstate Monica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 04:46:03