[Qgis-developer] Qgis Api - get a layer by its name

Carson Farmer carson.farmer at gmail.com
Tue Nov 9 11:03:10 EST 2010


Hi Kimaidou,

> I have not found any function in QgsMapLayer for getting a layer by its
> name. I needed it on a python plugin to let the user choose a layer from a
> combo box (already populated with the layer names)
> So I created this function http://osgeo.pastebin.com/7EpNA3JL
I suspect that is how most plugin developers have implemented this
functionality, and for the most part it works (save for the situations
you listed below).
>
> I have some questions regarding it:
> * Is it the right way ?
> * I have seen it is possible in Qgis to rename a layer, and 2 layers of the
> same type can have the same name. This makes my function not working in all
> the cases (which is my problem of course). Is there a reason to allow layers
> to share a name ?

One solution would be use userData to store the layers uniqueID, and
then use that to access layers later on.
First you add each layer name to the combobox, like so:
combobox.addItem ( layer.name(),QVariant(layer.getLayerID()))

and then when the user select a layer from the combobox, get the
maplayer by doing something like (untested):
uniqueId = combobox.itemData(combobox.currentIndex()).toString()
layer = QgsMapLayerRegistry.instance().mapLayer(uniqueId)

Of course, if you are simply listing all layers in the layer list,
then you could just use their order in the combobox, as this will be
the same as the order in the layer list.
layer = mapCanvas.layer(combobox.currentIndex())

Hope that helps,

Carson

-- 
Carson J. Q. Farmer
ISSP Doctoral Fellow
National Centre for Geocomputation
National University of Ireland, Maynooth,
http://www.carsonfarmer.com/


More information about the Qgis-developer mailing list