[Qgis-developer] Working with the new Legend

Martin Dobias wonder.sk at gmail.com
Fri Jun 27 23:11:33 PDT 2014


Hi Gary

On Sat, Jun 28, 2014 at 4:20 AM, Gary Sherman <gsherman at geoapt.com> wrote:
> Having read the thread about the new legend merge, I'm wondering if there is
> a summary on how to work with it via Python.

There is no Python-specific summary, but the doxygen documentation of
the new QgsLayerTree* classes should give you a good idea where to
start. I plan to add some notes to the PyQGIS cookbook later.


> I have a plugin that is broken as it relied on being able to move layers up
> and down in the legend by grabbing a reference to the QTreeWiget (now gone)
> and working with the Qt methods available to it.
>
> I need to:

Let me paste some example code. Let's prepare few things to begin with:

# add few layers at the beginning so the legend is not completely empty
v1 = iface.addVectorLayer("Point", "Layer 1", "memory")
v2 = iface.addVectorLayer("Point", "Layer 2", "memory")
v3 = iface.addVectorLayer("Point", "Layer 3", "memory")

# create a layer and add it to registry, saying it should not be
immediately added to legend
v4 = QgsVectorLayer("Point", "Layer X", "memory")
QgsMapLayerRegistry.instance().addMapLayer(v4, False)

# get reference to the layer tree
root=QgsProject.instance().layerTreeRoot()


> * insert a layer at a give location

# add layer to the node at index 0
v4n = QgsLayerTreeLayer(v4)
root.insertChildNode(0, v4n)


> * move a layer to a new position

v4n2 = v4n.clone()
root.insertChildNode(-1, v4n2) # insert at last position
root.removeChildNode(v4n)


> * remove a layer

root.removeChildNode(v4n2)

(we could use root.findLayer(v4.id()) to get the node if we didn't
have it before)


> It seems we could provide a higher level interface for moving layers around.
> The method of adding an existing layer to the legend in a new position then
> deleting its twin didn't work for me.

How do you mean it with a higher level interface - moving layers
around requires just two lines of code...

Regards
Martin


More information about the Qgis-developer mailing list