【发布时间】:2018-03-28 11:09:45
【问题描述】:
我正在尝试在树视图中加载子项
+top
parent1
parent2
parent3
首先,我仅使用父节点信息填充模型并将其附加到树视图,树看起来如上所示。
self.mytreeview=QtGui.Qtreeview()
self.model=QtGui.QStandardItemModel(self.mytreeview)
def initialise_model(self):
'''Populate the model with parent nodes only'''
#open file and process each line, each file line has the parent node info
....
for file_name_entry in fileobject:
parent_item=QtGui.QStandardItem(str(file_name_entry).strip())
parent_item.setData("this is a parent",QtCore.Qt.TooltipRole)
self.model.appendRow(parent_item)
self.mytreeview.setModel(self.model)
此时,父母都没有任何孩子的信息。 我接下来要做的是更新父节点,当用户点击父节点时(及时或延迟加载父子信息)。
所以当一个父节点被点击时,就会发出信号
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked(QModelIndex)'), self.update_model)
update_model 代码应该去获取父节点的子节点、更新模型、刷新树并展开父节点。
def update_model(self,index):
'''Update the model by adding children to selected/clicked parent node only'''
parent_node=QtGui.QStandardItem(self.model.itemFromIndex(index))
parent_item_index=index.row()
#open the file called parent_node.txt and get all the child entries from the file...
child_index=0
for child_name_entry in parent_text_fileobject:
child_item=QtGui.QStandardItem(str(child_name_entry).strip())
child_item.setData("this is a child",QtCore.Qt.TooltipRole)
parent_item.setChild(child_index,child_item)
child_index=child_index+1
#Once all the children have been added update the model, by inserting a new row where the parent was
self.model.removeRow(parent_item_index)#remove old parent
self.model.insertRow(parent_item_index,parent_item)#insert new parent with its children
当我尝试删除选定的父节点(没有子节点的那个)并尝试插入一个新的父项(有子节点)时,它最终会在没有子节点的父节点上方添加新的父节点(有子节点)所以我最终得到重复的父节点
+top
parent1
parent2
+parent2
child_a
child_b
child_c
parent3
所以只是回顾一下,删除和插入即
#Once all the children have been added update the model, by inserting a new row where the parent was
self.model.removeRow(parent_item_index)#remove old parent
self.model.insertRow(parent_item_index,parent_item)#insert new parent with its children
是个坏主意。看着 cmets,有人建议 AppendRow() 可能是答案,但我不太确定 我相信
self.model.appendRow(parent_item)#new parent with its children
只需将父节点添加到我的模型底部,因此树仍然会有重复的父节点,即
+top
parent1
**parent2**
parent3
**+parent2**
child_a
child_b
child_c
我认为我正在寻找一种更新模型中现有节点的方法,以便可以使用其子节点更新所选(父节点)。例如
...
self.model.UpdateExisitingNode(node_index)
...
关于如何更新模型中的节点有什么建议吗? 注意我使用的是 Windows 和 PyQt
问候
【问题讨论】:
-
我有点混淆了你的描述,澄清一下我想问你child_a,child_b和child_c存在并且只是想扩大看到它们?或者您要单击 parent2 来创建和添加这些孩子吗?
-
如果您已经填充了模型,树也会自动填充。所以你的问题没有多大意义。代码描述没有用 - 在您的问题中显示您的实际代码。
-
听起来好像您正在寻找类似 @987654321@ 和 fetches data 的即时信息。
-
我推荐使用第一种方法(wuth
appendRow)。你现在做的事情更难做对了。 -
@titusjan,仅父节点的条目数可能有数千个,每个父节点可能有数百个子节点,在将其附加到树视图之前填充整个模型似乎很耗时,特别是考虑到一些的父节点可能永远不会被点击
标签: python qt pyqt pyqt4 qtreeview