PyQGIS Layers Panel – How to Select Subgroup in Layers Panel

group-layerpyqgis

I can select a group layer (for example C) using the following script. But I can only select groups in root level (A or C). I am struggling to select subgroups. I play with the script, but no success.

name = 'C'

view = iface.layerTreeView()
m = view.model()

listIndexes = m.match(m.index(0, 0), Qt.DisplayRole, name, Qt.MatchFixedString)
    
if listIndexes:
    i = listIndexes[0]
    view.selectionModel().setCurrentIndex(i, QItemSelectionModel.ClearAndSelect)
    

enter image description here

How can I select a subgroup (B, D or E) in Layers panel?

Best Answer

Setting the Qt.MatchRecursive flag as parameter enables searching the entire hierarchy of the tree view.

And looking at the docs for QAbstractItemModel::match it also seems that you put the Qt.MatchFlags parameter in a wrong position. It should follow after parameter hits, which is a number specifying the amount of search results to look for.

I've adjusted the example script:

name = 'E'

view = iface.layerTreeView()
m = view.model()

listIndexes = m.match(m.index(0, 0), Qt.DisplayRole, name, 1, Qt.MatchFixedString | Qt.MatchRecursive)
    
if listIndexes:
    i = listIndexes[0]
    view.selectionModel().setCurrentIndex(i, QItemSelectionModel.ClearAndSelect)
Related Question