QTreeWidgetItem未获得Checked

时间:2018-04-16 19:25:12

标签: python-3.x pyqt

我正在尝试在初始化树之后检查函数中的树项。复选标记永远不会出现我不确定是否需要“刷新”树或者我没有与正确的对象进行交互。

我已经阅读了很多关于这个小部件的内容,我在几个网站上或多或少地看到了相同的问题,但答案是8年以上,两页代码,或者我只是不理解它们。

我在这里做错了什么?当我调用checkActiveTreeItems()时,为什么树中没有显示复选标记?

在REST调用之后,我想更新树中的已检查项目。这似乎没问题,但项目永远不会被检查。

def checkActiveTreeItems(self):
    for label in self.transactie['transactie']['labels']:
        test = QtWidgets.QTreeWidgetItem([label])
        test.setCheckState(0, QtCore.Qt.Checked)

这是创建树的函数,在上面的函数中将QTreeWidgetItem设置为Checked之后我不再调用它。

def initTree(self):
    print("initTree")
    self.treeWidget = QtWidgets.QTreeWidget(self.gridLayoutWidget)

   self.treeWidget.setSelectionMode(QtWidgets.QAbstractItemView.ContiguousSelection)
    self.treeWidget.setObjectName("treeWidget")

    inkomstenstructuur = requests.get(url="http://localhost:32769/_db/piekenpijp/incoming/inkomstenstructuur")
    iscontent = json.loads(inkomstenstructuur.content)
    self.inkomsten = iscontent
    inkomstentree = QtWidgets.QTreeWidgetItem(["Inkomsten"])

    for groep in iscontent:
        child = QtWidgets.QTreeWidgetItem([groep['groep']])
        inkomstentree.addChild(child)
        for categorie in groep['categorien']:
            child2 = QtWidgets.QTreeWidgetItem([categorie])
            child2.setCheckState(0, QtCore.Qt.Unchecked)
            child.addChild(child2)

    uitgavenstructuur = requests.get(url="http://localhost:32769/_db/piekenpijp/incoming/uitgavenstructuur")
    uscontent = json.loads(uitgavenstructuur.content)
    self.uitgaven = uscontent
    uitgaventree = QtWidgets.QTreeWidgetItem(["Uitgaven"])

    for groep in uscontent:
        child = QtWidgets.QTreeWidgetItem([groep['groep']])
        uitgaventree.addChild(child)
        for categorie in groep['categorien']:
            child2 = QtWidgets.QTreeWidgetItem([categorie])
            child2.setCheckState(0, QtCore.Qt.Unchecked)
            child.addChild(child2)

    self.treeWidget.itemChanged.connect(self.vinkje)

    self.treeWidget.resize(500, 200)
    self.treeWidget.setColumnCount(1)
    self.treeWidget.setHeaderLabels(["Categorie"])
    self.treeWidget.addTopLevelItem(inkomstentree)
    self.treeWidget.addTopLevelItem(uitgaventree)
    self.treeWidget.expandItem(uitgaventree)
    self.gridLayout.addWidget(self.treeWidget, 0, 2, 1, 1)

1 个答案:

答案 0 :(得分:0)

您当前的方法会创建一个 new 项,设置其检查状态,然后在不使用它的情况下抛弃它。相反,您需要在已创建的树中find the items

def checkActiveTreeItems(self):
    for label in self.transactie['transactie']['labels']:
        for item in self.treeWidget.findItems(label, Qt.MatchExactly):
            item.setCheckState(0, QtCore.Qt.Checked)