I need to find a layer in the TOC and get its position (which can vary) so that I can add a group after that layer. I can get the layer I want to reference easily enough:

root = QgsProject.instance().layerTreeRoot()
last_layer = QgsProject.instance().mapLayersByName('next_ids')[0]

What I want to do is add group after that layer:

lyr_pos = [index in TOC of last_layer]  # This is what I need to get
self.err_group = root.insertGroup(lyr_pos + 1, GROUP_NAME)

You need the layer index relative to its parent group, and then you use such parent group to finally insert your new group, in this way:

# Get relevant objects
root = QgsProject.instance().layerTreeRoot()
layer_node = root.findLayer(layer)  # layer is a QgsMapLayer
parent_group = layer_node.parent()

# Get layer index
idx = parent_group.children().index(layer_node)

# Now insert the new group!
parent_group.insertGroup(idx + 1, "New Group")
  • Thanks German. I managed it in similar fashion, but I believe your way is cleaner than my solution. – CNIDog Nov 4 '20 at 19:04
  • You're welcome. Yes, it's very close, although you do need the parent group (not only the root) to make it more generic, i.e., to make it work also inside subgroups. – Germán Carrillo Nov 4 '20 at 20:41

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.