8

I am trying move/position a layer to the bottom of the TOC by using addTopLevelItem on all other layers. I unsure how to reference the layers as QTreeWidgetItem's.

def bg_bottom_level_item(self):
    layers = self.canvas.layers()
    layerlist = []
    for layer in layers:
        layerID = str(layer.id())
        if "Auto_Background" not in layerID:
            layerlist.append(layer)
        else:
            pass
    for layer in layerlist:
        leg = qgis.utils.iface.mainWindow().findChild(QTreeWidget, 'theMapLegend')
        item = QTreeWidgetItem(layer)
        leg.addTopLevelItem(item)

Error:

QTreeWidgetItem(QTreeWidgetItem): argument 1 has unexpected type 'QgsRasterLayer'

Or does anyone have another solution for moving layers around in the TOC?

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
Matt
  • 2,706
  • 2
  • 25
  • 38
  • 1
    Check out this post, http://gis.stackexchange.com/questions/41977/sort-layers-in-qgis-table-of-contents – artwork21 Apr 17 '14 at 12:18

1 Answers1

6

By using the new Layer tree (aka legend or Toc) added by Martin Dobias since QGIS v.2.4, you can load a layer to the bottom of the ToC following these steps:

  1. Get a reference of the layer tree

    root = QgsProject.instance().layerTreeRoot()
    
  2. Create the layer object

    mylayer = QgsVectorLayer("/Path/to/your/data.shp", "my layer", "ogr")
    
  3. Add the layer to the QGIS Map Layer Registry

    QgsMapLayerRegistry.instance().addMapLayer(mylayer, False)
    
  4. Append the layer to the layer tree

    root.addLayer(mylayer)
    

If you want to move an existing layer to the bottom of the ToC, you need to know the layer id (you can get it by executing root.findLayerIds()). Once you get the layer id, follow these steps:

a. Same as 1.

root = QgsProject.instance().layerTreeRoot()    

b. Get layer by id

myExistingLayer = root.findLayer("divipola_mpio20141217144143371")

c. Clone it (trust me)

myClone = myExistingLayer.clone()

d. Append the clone to the layer tree

root.addChildNode(myClone)

e. Get the original layer's parent

parent = myExistingLayer.parent()

f. Remove the original layer

parent.removeChildNode(myExistingLayer)

Edit: Now steps a. to f. should work for any layer/group regardless of its position in the layer tree hierarchy.

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178