If in QGIS TOC a group already exists and I add a new layer via

QgsVectorLayer* lyr= mQGisIface->addVectorLayer(uri->uri(),Title, myProviderName);

the new layer will be inserted within the group. How can I move it outside/above the group?

  • didn't tested it until yet, the problem is buried on my desk... – Ms. Smith Apr 9 '15 at 13:05

You can do that by following these steps (QGIS >= v.2.4):

  1. Get the layer tree object

    root = QgsProject.instance().layerTreeRoot()

  2. Find the desired group by name

    mygroup = root.findGroup("group1")

  3. Get the group index

    parentGroup = mygroup.parent() groupIndex=-1 for child in parentGroup.children(): groupIndex+=1 if mygroup == child: break

  4. Create the new layer object

    mylayer = QgsVectorLayer("/PathToYour/data.shp", "my layer", "ogr")

  5. Add the layer to the QGIS Map Layer Registry

    QgsMapLayerRegistry.instance().addMapLayer(mylayer, False)

  6. Insert the layer above the group

    parentGroup.insertChildNode(groupIndex, QgsLayerTreeLayer(mylayer))

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.