[Qgis-developer] Working with the new Legend

Gary Sherman gsherman at geoapt.com
Sat Jun 28 00:06:06 PDT 2014


On 6/27/14 10:11 PM, Martin Dobias wrote:
> 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.
>
Great
>
>> 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...

Agreed. After seeing your examples, it looks fine.

Thanks!

-gary

>
> Regards
> Martin
>


-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Gary Sherman

Founder, QGIS Project
Consulting: geoapt.com
Publishing: locatepress.com

We work virtually anywhere
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


More information about the Qgis-developer mailing list