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,...)?

closed as too broad by PolyGeo Aug 25 at 6:29

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

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

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