如何过滤出QTreeWidgetItemIterator中不可检查的结果?

2024-09-30 20:21:34 发布

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

是否可以过滤QTreeWidgetItemIterator,以便从结果中省略不可检查的项?你知道吗

TreeList = ({
    'Header1': (('Item11', 'Item12', )),
    'Header2': (('Item21', 'Item22', )),
})

# LOCATED IN `initLayout` METHOD
for key, value in TreeList.items():
    parent = QTreeWidgetItem(self.ListTreeView, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

# LOCATED IN `initialize` METHOD
iterator = QTreeWidgetItemIterator(self.ListTreeView)
while iterator.value():
    val = iterator.value()

    try:  # Results in object has not attribute
        if val.isCheckable():
            print('checkable')
    except AttributeError as e:
        print(e)

    iterator += 1

在本例中,Header1Header2都不是可检查的,但是位于它们下面的项是可检查的。当我遍历QTreeWidget时,它返回整个列表。你知道吗

查看IteratorFlags的文档,我可以看到可以设置一些标志,但我不知道如何在Python中设置它们,而且我不确定它们是否符合我的需要。你知道吗

现在,val.isCheckable()会产生一个AttributeError;这是意料之中的,因为isCheckable()似乎不是QTreeWidgetItem的属性—或者是?你知道吗

最好我想过滤掉不可检查的项目,但是如果这是不可能的,我如何检查值isCheckable()?你知道吗


Tags: inchildforvaluevalmethoditeratorqtreewidgetitem
1条回答
网友
1楼 · 发布于 2024-09-30 20:21:34

默认情况下,QTreeWidgetItem类是可检查的,并且没有可检查状态的访问器方法。因此,您需要改用项标志:

iterator = QTreeWidgetItemIterator(self.ListTreeView)
while iterator.value():
    val = iterator.value()
    if val.flags() & Qt.ItemIsUserCheckable:
        print('checkable')
    iterator += 1

考虑到这一点,您还需要显式地取消设置不希望检查的项的标志:

for key, value in TreeList.items():
    parent = QTreeWidgetItem(self.ListTreeView, [key])
    # remove checkable flag for header items
    parent.setFlags(parent.flags() & ~Qt.ItemIsUserCheckable)

相关问题 更多 >