PyQt如何在QTreeVi中单击时传递索引

2024-09-28 21:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,里面有树形的数据:

tree = {'parent 1': {'child 1 - 1': {'child 1 - 1 - 1': {'child 4 levl parent 1': {}}}, 'child 1 - 2': {'children 2- 1': {}}, 'child 1- 3': {}}, 'parent 2': {'parent 2- 1 - chil': {}}, 'parent 3': {}, 'parent 4': {}}

接下来,我为这本词典建立一个列表:

def treeRubrics(self):
    self.treeList = QtWidgets.QTreeView()
    self.treeList.setObjectName("treeList")
    self.treeList.setMinimumSize(QtCore.QSize(200, 0))
    self.treeList.setMaximumSize(QtCore.QSize(200, 16777215))
    self.gridLayout.addWidget(self.treeList, 3, 0, 1, 1)
    model = QtGui.QStandardItemModel()
    self.populateTree(self.tree, model.invisibleRootItem())
    self.treeList.setModel(model)
    model.setHeaderData(0, QtCore.Qt.Horizontal, 'Records tree')
    self.treeList.expandAll()
    self.treeList.selectionModel().selectionChanged.connect(self.onSelectionChanged)
    __sortingEnabled = self.treeList.isSortingEnabled()
    self.treeList.setSortingEnabled(__sortingEnabled)

我将鼠标单击列表中的一个项目:

def onSelectionChanged(self, *args):
    for sel in self.treeList.selectedIndexes():
        val = "/"+sel.data()
        while sel.parent().isValid():
            sel = sel.parent()
            val = "/" + sel.data()+ val

但这就是为什么我只能得到一个选定姓名的列表,例如: /parent 1/child 1 - 1/child 1 - 1 - 1/child 4 levl parent 1

如何更改dict“tree”和代码,使树的每个元素都有自己的索引,并在单击时传递此记录的索引(在方法onSelectionChanged中获取此索引)?你知道吗


Tags: selfchildtree列表modeldefvalparent