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?
-
2Perhaps this post might help: Determining if a group in legend is selected, using PyQGIS– JosephCommented Aug 22, 2018 at 9:37
Add a comment
|
1 Answer
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.
-
-
@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 hadiface.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 yourselect
function so that it can be selected as well. Commented Feb 14, 2022 at 16:40