Monday, 3 February 2020

qgis plugins - Determining if a group in legend is selected, using PyQGIS


How can I determine in code (python or c++) whether a group in legend is selected or not?


mQGisIface->legendInterface()->selectedLayers() 

gives me only selected layers and no groups, and in QgsLegendInterface I doesn't find anything about it.


I use QGIS Version 2.14.4.




Answer



You can use QgsLayerTreeView (accessible from the iface object) for that. I didn't find a direct way (QgsLayerTreeGroup doesn't seem to have a method for that), but you can simply reuse the following function:


def isMyGroupSelected( groupName ):
myGroup = QgsProject.instance().layerTreeRoot().findGroup( groupName )
return myGroup in iface.layerTreeView().selectedNodes()

print isMyGroupSelected( 'my group name' )

Note that iface.layerTreeView().selectedNodes() gives you a list of selected nodes in the legend, which you could use directly, depending on your use case (e.g., print names of selected groups).





EDIT: For reference, this is the C++ code that you told me you ended up using:


QList selNodes= mQGisIface->layerTreeView()->selectedNodes(true);
for (int i=0;i QgsLayerTreeNode * selNode=selNodes.at(i);
if(selNode->nodeType==QgsLayerTreeNode::NodeType::NodeGr‌​oup) {
...

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...