在 QTreeView 中,可以通过使用 QStandardItemModel 来实现树状结构。要向子项的子项中添加内容,您需要获取特定的父项,并在其下添加子项。
以下是一个示例代码,演示如何向 QTreeView 的树状结构中添加子项的子项:
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QStandardItemModel, QStandardItem
if __name__ == '__main__':
app = QApplication([])
window = QMainWindow()
# 创建模型
model = QStandardItemModel()
model.setHorizontalHeaderLabels(['Tree'])
# 添加根节点
root_item = QStandardItem('Root')
model.appendRow(root_item)
# 添加父节点
parent_item = QStandardItem('Parent')
root_item.appendRow(parent_item)
# 添加子节点
child_item1 = QStandardItem('Child 1')
parent_item.appendRow(child_item1)
# 获取父节点并向其下添加子项的子项
parent_index = parent_item.index()
grandchild_item1 = QStandardItem('Grandchild 1')
# Here is the key part: Getting the child of a parent item and appending another child to it.
# The index() function returns the QModelIndex for an item in the model.
# We can then use that index to get the corresponding item and append more children to it.
child_index_1= child_index.index()
grandchild2=Qstandaarditem("grandcild2")
model.itemFromIndex(child_index).appendRow(grandchild2)
'''
注意:以上代码只是一个示例,用于说明如何向树状结构中的子项的子项中添加内容。
实际使用时,您可能需要根据自己的需求进行修改和扩展。
'''
# 设置模型
tree_view = QTreeView()
tree_view.setModel(model)
window.setCentralWidget(tree_view)
window.show()
app.exec()
这是一个简单的示例,您可以根据实际需求进行修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问