3

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.

4

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<QgsLayerTreeNode *> selNodes= mQGisIface->layerTreeView()->selectedNodes(true);
for (int i=0;i<selNodes.count();i++) { 
    QgsLayerTreeNode * selNode=selNodes.at(i);       
    if(selNode->nodeType==QgsLayerTreeNode::NodeType::NodeGr‌​oup) {
        ...
  • 1
    Yes, you are right. I have to use the QgsLayerTreeView. In c++ it is so: QList<QgsLayerTreeNode *> selNodes= mQGisIface->layerTreeView()->selectedNodes(true);for (int i=0;i<selNodes.count();i++) { QgsLayerTreeNode * selNode=selNodes.at(i); if(selNode->nodeType==QgsLayerTreeNode::NodeType::NodeGroup) {... Thank you a lot! – Ms. Smith Sep 22 '16 at 7:30
  • 1
    I don't think that's another answer @Joseph. I've updated my answer with schmiddor's code for reference. – Germán Carrillo Sep 22 '16 at 11:44
  • 1
    @GermánCarrillo - Fair point and nice one! – Joseph Sep 22 '16 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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