如何以编程方式突出显示 QTreeWidget 中的选择?

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

当我使用

QTreeWidget
以编程方式在
item_selected('Item2')
中选择一个选项时,该选项将按预期传递到处理程序。我还希望该项目有一个选择突出显示,但我似乎无法弄清楚。有什么想法吗?

from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
import sys


def item_selected(selection):
    try:
        print(selection.text(0))
    except AttributeError:
        print(selection)


app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item11', 'Item21', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

tree.itemClicked.connect(item_selected)

tree.show()

# SELECT AND HIGHLIGHT THIS ONE
item_selected('Item2')

sys.exit(app.exec_())

如果上面的代码有点混乱,抱歉。

python python-3.x pyqt pyqt5 qtreewidget
1个回答
2
投票

您不能使用相同的插槽,它接收一个项目,并且仅打印它,在您的情况下,您必须搜索该项目的文本并选择它:

def item_selected(selection):
    print(selection.text(0))

app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item11', 'Item21', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

tree.itemClicked.connect(item_selected)

items = tree.findItems("Item2", Qt.MatchFixedString| Qt.MatchRecursive) 
[it.setSelected(True) for it in items]

tree.expandAll()
tree.show()

sys.exit(app.exec_())

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