Lines length plugin - QgsVectorLayer error

by monica   Last Updated June 13, 2019 00:22 AM

Several similar questions have already been made, but none of the is helping me.

I have a layer of polygons and I want to known the length of each line of each polygon. And based on the length I want to create another layer. So I convert polygons > line and apply the explode lines tool. But then when I try to get the length, this is the error: AttributeError: QgsVectorLayer object has no attribute geometry.

My code is this:

def run(self):
   # show the dialog
    layers = QgsMapLayerRegistry.instance().mapLayers().values()

    for layer in layers:
        if layer.type() == QgsMapLayer.VectorLayer:
            self.dlg.layerCombo.addItem(, layer )
    result = self.dlg.exec_()
    # See if OK was pressed
    if result == 1:
        index = self.dlg.layerCombo.currentIndex()
        layer = self.dlg.layerCombo.itemData(index)
        #polygons to lines
        processing.runalg ('saga:convertpolygonstolines',layer,layer_line)

I know I need to use somenthing like this to have a new field with length values:

for f in features:
        geom = f.geometry()
        leng = geom.length()
        res = layer.dataProvider().addAttributes([QgsField("Length", QVariant.Int)])
        fieldIndex = layer.dataProvider().fieldNameIndex( "Length" )

I know that my problem is using QgsMapLayer.VectorLayer...But I don't know whatelse to use. I already read PyQGIS Developer Cookbook, the answer to this question (Calculate length of selected features in PyQGIS), this question (Adding new field with expression in pyqgis) ...

What should I use instead of QgsVectorLayer?

Related Questions

Updated February 25, 2019 12:22 PM

Updated July 02, 2019 13:22 PM

Updated August 20, 2019 16:22 PM

Updated August 17, 2016 08:09 AM

Updated March 05, 2018 21:22 PM