简体   繁体   English

PyQt4 Qtreewidget-如果选中子复选框,则获取层次结构文本

[英]PyQt4 Qtreewidget - get hierarchy text if child checkbox is checked

What I am currently trying to do is take a populated tree (qtreewidget) that has checkboxes at the bottom child level, and return the text of the path to the child if the box is checked. 我目前正在尝试做的是填充一个填充的树(qtreewidget),该树的底部子级具有复选框,如果选中该框,则将路径文本返回到子级。 The reason I want to do this, is if a child is checked, it will then change a value in a key in a dictionary. 我要执行此操作的原因是,如果选中了一个子项,则它将更改字典中某个键的值。 (The "raw" dictionary the tree was created from). (从中创建树的“原始”字典)。 Here's a visual example of what I mean: 这是我的意思的直观示例:

  1. From user input and server directory crawling, we have populated a tree that looks something like this: (Only the lowest level child items have checkboxes.) And sorry for the horrible tree diagram!! 通过用户输入和服务器目录爬网,我们填充了一棵看起来像这样的树:(只有最低级别的子项具有复选框。)对于这棵可怕的树图,我们深表歉意! Hopefully it makes sense... 希望这是有道理的...

edited 编辑

study 研究

-subject 1 -主题1

--date - 日期

---[]c - -[]C

---[]d --- [] d

---[]e --- []ë

-subject 2 -主题2

--date - 日期

---[]g - -[]G

---[]h - -[]H

  1. If someone checks (for example) the "g" levle child, is there anyway to then get the path to "g" in a form something like [1, B, g] or 1-Bg or 1/B/g, etc.? 如果有人检查(例如)“ g”级孩子,则无论如何都会以[1,B,g]或1-Bg或1 / B / g等形式获取“ g”的路径。?

  2. One of the children levels (let's say in the example A and B) are also set to be user editable. 子级别之一(例如在示例A和B中)也被设置为用户可编辑的。 So I'd need the info from the tree, not the info the tree was originally populated from. 因此,我需要树中的信息,而不是树的原始信息。

I have tried printing self.ui.treeWidget indexes with no real luck in getting what I want. 我尝试打印self.ui.treeWidget索引,但并没有真正获得我想要的运气。 I feel as though there is an easy solution for this, but I can't seem to find it. 我觉得似乎有一个简单的解决方案,但是我似乎找不到。 Hopefully someone can help! 希望有人可以提供帮助!

Actual Code Snippet: 实际代码段:

    for h,study in enumerate(tree_dict['study']):
        study_name = study['study_name']
        treeSTUDY = QtGui.QTreeWidgetItem(self.ui.treeWidget, [study_name])
        treeSTUDY.setFlags(QtCore.Qt.ItemIsEnabled)
        self.ui.treeWidget.expandItem(treeSTUDY)            

        for i,subject in enumerate(study['subject']):
            subject = subject['ID']
            treeSUBJECT = QtGui.QTreeWidgetItem(treeSTUDY, [subject_id])
            treeSUBJECT.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled)

            for j,visit in enumerate(subject['visit']):
                scan_date = visit['date']                     
                treeDATE = QtGui.QTreeWidgetItem(treeSUBJECT, [scan_date[4:6])
                treeDATE.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled)

                for k,ser in enumerate(visit['series']):
                    s_name = ser['name'] + '-' + ser['description']
                    count =  str(ser['count'])
                    treeSCAN = QtGui.QTreeWidgetItem(treeDATE)
                    treeSCAN.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
                    treeSCAN.setCheckState(0, QtCore.Qt.Unchecked)   
                    treeSCAN.setText(0, s_name)
                    treeSCAN.setText(1, ser['time'])
                    treeSCAN.setText(2, ser['number'])
                    treeSCAN.setText(3, 'count')

All you need is a method that walks up the parent/child chain grabbing the text of each item until the parent is None : 您需要的是一个沿着父/子链移动的方法,以获取每个项目的文本,直到父None为止:

def getTreePath(self, item):
    path = []
    while item is not None:
        path.append(str(item.text(0)))
        item = item.parent()
    return '/'.join(reversed(path))

UPDATE : 更新

Here is a demo script that shows how to get the checked item and retrieve its path: 这是一个演示脚本,显示了如何获取选中的项目并检索其路径:

from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.tree = QtGui.QTreeWidget(self)
        self.tree.setHeaderHidden(True)
        for index in range(2):
            parent = self.addItem(self.tree, 'Item%d' % index)
            for color in 'Red Green Blue'.split():
                subitem = self.addItem(parent, color)
                for letter in 'ABC':
                    self.addItem(subitem, letter, True, False)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        self.tree.itemChanged.connect(self.handleItemChanged)

    def addItem(self, parent, text, checkable=False, expanded=True):
        item = QtGui.QTreeWidgetItem(parent, [text])
        if checkable:
            item.setCheckState(0, QtCore.Qt.Unchecked)
        else:
            item.setFlags(
                item.flags() & ~QtCore.Qt.ItemIsUserCheckable)
        item.setExpanded(expanded)
        return item

    def handleItemChanged(self, item, column):
        if item.flags() & QtCore.Qt.ItemIsUserCheckable:
            path = self.getTreePath(item)
            if item.checkState(0) == QtCore.Qt.Checked:
                print('%s: Checked' % path)
            else:
                print('%s: UnChecked' % path)

    def getTreePath(self, item):
        path = []
        while item is not None:
            path.append(str(item.text(0)))
            item = item.parent()
        return '/'.join(reversed(path))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 250, 450)
    window.show()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM