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

PyQt:获取QStandardItemModel.appendRow()添加行的QModelIndex

获取QStandardItemModel新增行的QModelIndex并选中

核心逻辑

新增行的行号为 model.rowCount() - 1(行索引从0开始计数,appendRow执行后总行数加1,最后一行的索引即为总行数减一),通过model.index()方法即可获取该行的QModelIndex,再结合QItemSelectionModel实现整行选中。

代码示例

# 假设已完成model、item1/item2/item3的初始化,且视图view已通过view.setModel(model)关联模型
model.appendRow([item1, item2, item3])

# 获取新增行的行号
new_row_idx = model.rowCount() - 1
# 获取该行任意一列的QModelIndex(此处取第0列)
target_index = model.index(new_row_idx, 0)

# 获取视图的选择模型
selection_model = view.selectionModel()
# 选中整行:Rows模式确保选中整行,SelectCurrent保留原有选中(替换选中用ClearAndSelect)
selection_model.select(target_index, Qt.ItemSelectionModel.SelectCurrent | Qt.ItemSelectionModel.Rows)

注意事项

  • 必须确保视图与模型已通过view.setModel(model)关联,否则selectionModel()会返回空对象
  • 选择模式可按需调整:
    • Qt.ItemSelectionModel.ClearAndSelect:清除原有选中状态,仅选中当前行
    • Qt.ItemSelectionModel.Add:在原有选中基础上追加选中当前行

内容的提问来源于stack exchange,提问作者knipknap

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:08:09