Search code examples
pythonpython-3.xpyqtpyqt5qtreewidget

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.


Solution

  • 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