I am developing a plugin, and I want user to select one of the loaded layers from a combobox. I've already coded this much:

    layerlist = []
    self.dlg.ui.layerCombo.clear()  # clear the combo 
    layermap = QgsMapLayerRegistry.instance().mapLayers()
    for name, layer in layermap.iteritems():
        if layer.type() == QgsMapLayer.VectorLayer:
            if layer.geometryType() == QGis.Line:
                layerlist.append( unicode( layer.name() ) )
    for layer in layerlist:    # foreach layer in legend 
        self.dlg.ui.layerCombo.addItem( layer ) 

First Question: I get the error

IndexError: list index out of range

which I don't quite know why.

Second Question: Am I doing the right thing? I couldn't find a tutorial on this. Where is the best place to put this code (run, initGui,...)?

Any help is greatly appreciated!

layers = QgsMapLayerRegistry.instance().mapLayers().values()
for layer in layers:
    if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line:
       self.dlg.ui.layerCombo.addItem( layer.name(), layer ) 

You can then get the layer from the combo like this:

index = self.dlg.ui.layerCombo.currentIndex()
layer = self.dlg.ui.layerCombo.itemData(index)
  • Thanks alot, it works great! just a follow up question: I put the first part of code in "run" method. is that the right place in general? I guess I haven't really understood what run does exactly. – Alex Apr 25 '14 at 11:53
  • 1
    With the plugin builder default plugin, I had to remove ".ui" to make it work. Otherwise this is great! – underdark Apr 26 '14 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.