[Qgis-developer] Basic question: How to select a layer in the GUI
and get the handle in the Python code?
Giuseppe Sucameli
sucameli at faunalia.it
Thu Dec 8 07:46:28 EST 2011
Hi Ole,
On Thu, Dec 8, 2011 at 3:54 AM, Ole Nielsen
<ole.moller.nielsen at gmail.com> wrote:
> I am maybe looking for a file or layer selection combo and
> a hint on how to make it work.
First create a combo in your UI named "layerCombo"
Then populate the combo running:
self.layers = self.iface.legendInterface().layers() # store the layer list
self.layerCombo.clear() # clear the combo
for layer in self.layers: # foreach layer in legend
self.layerCombo.append( layer.name() ) # add it to the combo
When you have to get the layer selected in the combo,
just us the following snippet:
index = self.layerCombo.currentIndex()
if index < 0:
# it may occur if there's no layer in the combo/legend
else:
layer = self.layers[ index ] # get the layer by index from the
previous stored list
source = layer.source() # get the layer source
I haven't tried the previous code, so it could contains errors.
> I have very limited experience with UIs so please forgive me my basic
> questions.
Look at QT tutorials, they contain everything you need
to know about UI creation.
Cheers.
>
> Cheers and thanks
> Ole
>
> On Wed, Dec 7, 2011 at 8:57 PM, Alexander Bruy <alexander.bruy at gmail.com>
> wrote:
>>
>> 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
>
>
>
> _______________________________________________
> Qgis-developer mailing list
> Qgis-developer at lists.osgeo.org
> http://lists.osgeo.org/mailman/listinfo/qgis-developer
>
--
Giuseppe Sucameli
More information about the Qgis-developer
mailing list