9

I have seen ways to programmatically select a current layer using QgsLayerTreeView().setCurrentLayer() but I cannot find a way to change the group selection. Does anyone have any tricks/hacks that I can use or point me to the relevant Qgs class that I can use?

1

1 Answer 1

5

The following script selects a node by name.

from qgis.PyQt.QtCore import *

def select(name):
    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)
    else:
        raise Exception(f"'{name}' not found")
    
select("group1")

There are also different type of matches that can be used when searching nodes.

Limitation: It selects any kind of node (group or layer) at top-level, which means it doesn't select nodes in nested sublevels.

enter image description here

4
  • Any idea how to search inside nested levels as well. Commented Feb 14, 2022 at 4:32
  • @ar-siddiqui I coded a little script. It may help. -> github.com/kadirsahbaz/SUHULET Commented Feb 14, 2022 at 13:18
  • Thanks a lot. Once we have the group we want to set as current/active. How can we do that? I already have the group, I am struggling with making the group current/active. I tried the select function in your answer. That worked, but as you have mentioned not for the nested groups and I do have nested groups. I wish QGIS had iface.setActiveGroup() as that is all I need. Commented Feb 14, 2022 at 15:03
  • I should have been more clear in my first comment, when I said "search" I didn't mean just searching like iface.findGroup() but searching in your select function so that it can be selected as well. Commented Feb 14, 2022 at 16:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.