QTreeView清除QStandardItemModel后如何选中并高亮子项?
问题
清除QStandardItemModel以更新QTreeView中的数据后,无法选中并高亮之前选中的子项,仅能正常选中父项。例如本该选中子项Server 1,实际却选中了父项Group 1。相关代码如下:
flag = None index = self.treeView.currentIndex() # If selected parent if not index.parent().isValid(): col_parent = 0 row_parent = index.row() flag = True # if child elif index.parent().isValid(): child_index = self.treeModel.index(0,0,index.parent()) flag = False self.treeModel.clear() self.showDataInTree() # My method to fill QTreeView # Highlight last item if flag: self.treeView.setCurrentIndex( self.treeModel.index(row_parent,col_parent)) elif not flag: self.treeView.setCurrentIndex(child_index)
解决方案
问题核心在于:模型清空后,旧的QModelIndex会完全失效,直接使用旧模型的子项索引无法定位到新模型的对应位置。需要改为保存选中项的层级位置信息,更新后重新构建有效索引:
- 保存选中项的层级数据:
- 选中父项时,仅保存父项的行号
- 选中子项时,同时保存父项的行号和子项自身的行号
- 模型更新后,根据保存的位置信息重新获取新模型的索引:
- 子项需要先找到对应父项的新索引,再通过父项索引获取子项的新索引
修改后的代码示例:
# 保存选中项的位置信息 selected_parent_row = None selected_child_row = None index = self.treeView.currentIndex() if not index.parent().isValid(): # 选中的是父项 selected_parent_row = index.row() else: # 选中的是子项,保存父项行号和子项行号 selected_parent_row = index.parent().row() selected_child_row = index.row() # 清空模型并重新加载数据 self.treeModel.clear() self.showDataInTree() # 恢复选中状态 if selected_parent_row is not None: # 先获取父项的新索引 parent_index = self.treeModel.index(selected_parent_row, 0) if selected_child_row is not None: # 获取子项的新索引并选中 child_index = self.treeModel.index(selected_child_row, 0, parent_index) self.treeView.setCurrentIndex(child_index) else: # 选中父项 self.treeView.setCurrentIndex(parent_index)
内容的提问来源于stack exchange,提问作者ChainSaw
相关产品推荐
相关产品推荐

