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 Answer 1


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

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

  • Any idea how to search inside nested levels as well. Feb 14, 2022 at 4:32
  • @ar-siddiqui I coded a little script. It may help. -> github.com/kadirsahbaz/SUHULET 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. 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. Feb 14, 2022 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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