[Qgis-developer] Usefull methods

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Wed Dec 10 10:32:15 EST 2008


2008/12/10 vatto <mauricio.dev at gmail.com>:
> I've written some methods to work with layers' names. I found the usefull and
> usually being used in every script I make. Shouldn't these stuff be a default
> in the API? Well, the python code is here. It shouldn't be hard to translate
> do C++.

 I'd like to make a plugin of widely-useful python functions like this
for other plugins to use, called 'qutils'. But my worry is that then
we'd be defining our own API, and people would have to keep upgrading
their qutils plugin... It might get messy.

> def listLayers(self,layertype):
>    layersmap=QgsMapLayerRegistry.instance().mapLayers()
>    layerslist=[]
>    for (name,layer) in layersmap.iteritems():
>        if (layertype==layer.type()):
>            layerslist.append(layer.name())
>    return layerslist

 You can rewrite that more 'pythonically' as a one-liner:

def listLayers(layertype):
 return [z.name() for z in
QgsMapLayerRegistry.instance().mapLayers().values() if z.type() ==
layertype]

 Neat eh? Also, it doesn't need 'self' unless it's a class method.

> def getLayerByName(self,layerName):
>    layersmap=QgsMapLayerRegistry.instance().mapLayers()
>    for (name,layer) in layersmap.iteritems():
>        if (layerName==layer.name()):
>            return layer

 Qgis layer names aren't unique, so your code will get the first layer
with that name. I think (someone prove me wrong) the only unique way
of identifying a layer in Qgis is with the layer object itself. That
does mean that drop-down selection boxes can't rely on looking up text
names to find the right layer, and need to store the layer object
too.... Anyway, this can also be a pythonic one-liner that returns all
layers with that name:

def getLayerByName(name):
 return [str(z.name()) for z in
QgsMapLayerRegistry.instance().mapLayers().values() if z.name() ==
name]

Okay, sometimes one-liners aren't better but I thought you might like
to see how python "list comprehensions" work - once you start using
them you'll use them everywhere!

But yes, I agree we should try and sort out some common python
functionality into a plugin!

Barry


More information about the Qgis-developer mailing list