在PyQT6中的QTreewidget中查找并选择元素

问题描述 投票:0回答:1

如何使用元素的路径在 Qtreewidget 中选择该元素?

路径被写为示例字符串:parent/parent/parent/parent/element

沿整个路径搜索元素,而不仅仅是通过该元素的名称来搜索元素很重要,因为树中可能有很多具有相同名称的元素,但每个元素肯定会有不同的路径。

我尝试用十种方法来解决:

def find_and_select_item(self):
    path = self.comboBox_Scene.currentText()
    path_elements = path.split('/')
    current_item = self.treeWidget.invisibleRootItem()
    for element in path_elements:
        items = self.treeWidget.findItems(element, Qt.MatchFlag, 0)
        if items:
            current_item = items[0]
        else:
            # Element not found in the current level of the tree
            return None

    # Select the found item
    current_item.setSelected(True)
    return current_item

不幸的是,这个函数返回一个错误::

TypeError: findItems(self, text: str, flags: Qt.MatchFlag, column: int = 0): argument 2 has unexpected type 'EnumType'

python pyqt6 qtreewidget
1个回答
0
投票

试试这个:

def find_and_select_item(self):
    path = self.comboBox_Scene.currentText()
    path_elements = path.split('/')
    current_item = self.treeWidget.invisibleRootItem()

    for element in path_elements:
        items = self.treeWidget.findItems(element, Qt.MatchFlag, 0)
        if items:
            current_item = items[0]
            # Select the found item
            current_item.setSelected(True)
        else:
            # Element not found in the current level of the tree
            return None

    return current_item
© www.soinside.com 2019 - 2024. All rights reserved.