Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight selection in QTreeWidget programmatically?

When I choose a selection in the QTreeWidget programmatically using item_selected('Item2') the selection gets passed to the handler as expected. I would also like that item to have a selection highlight, but I can't seem to figure that out. Any ideas?

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_())

Sorry if the above code is a mess.

like image 969
artomason Avatar asked Jul 12 '26 03:07

artomason


1 Answers

you must not use the same slot, it receives an item, and only prints it, in your case you have to search the item for its text and select it:

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_())

enter image description here

like image 109
eyllanesc Avatar answered Jul 13 '26 16:07

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!