[Qgis-developer] Basic question: How to select a layer in the GUI and get the handle in the Python code?

Alexander Bruy alexander.bruy at gmail.com
Wed Dec 7 08:57:35 EST 2011


Hi Ole,

2011/12/7 Ole Nielsen <ole.moller.nielsen at gmail.com>:
> Sorry, I was perhaps not as clear as I could have been. I have already
> written plugins using the currentLayer option. What I need now is to combine
> two layers for a specific analysis. So I imagine being able to select them
> through the plugin GUI selection combos and return the two layer handles to
> the Python code in the same format as what is provided by current layer.
> However, I have no idea how to start doing this.

Ah, understand. That's not so difficult. You need to get layer name
from combobox,
then find layer by name. Here is small function that did this work for you

def getVectorLayerByName( layerName ):
  layerMap = QgsMapLayerRegistry.instance().mapLayers()
  for name, layer in layerMap.iteritems():
    if layer.type() == QgsMapLayer.VectorLayer and layer.name() == layerName:
      if layer.isValid():
        return layer
      else:
        return None

So in your code you can simply do something like this

layerA = getVectorLayerByName( self.cmbLayerA.currentText() )
layerB = getVectorLayerByName( self.cmbLayerB.currentText() )

Hope this helps

-- 
Alexander Bruy
NextGIS


More information about the Qgis-developer mailing list