QGIS – How to Fix AttributeError for QgsVectorLayer Geometry

geometrypyqgispythonqgis

Ok… So I am trying to add a column (Length) in attribut table that shows the length of each line of a line feature. A part of my code is this:

            geom = layer.geometry()
            len = geom.length()
            processing.runalg('qgis:fieldcalculator', layer_output2, 'Length', 0, 10, 2, True, len, layer_output2)

And the error says that QgsVectorLayer has no attribute 'geometry'…What am I missing?

QgsVectorLayer is here:

    for layer in layers:
        if layer.type() == QgsMapLayer.VectorLayer:
            self.dlg.layerCombo.addItem( layer.name(), layer )

Maybe my data has a problem…but everything else I try to do, worked.
So, maybe my code is wrong…(probably, I am not good at coding).
Any tips?

Best Answer

Let’s point out some useful information: 1 - A layer has features. 2 - A feature has a geometry

With that in mind, you need to iterate over the features in your layer. For each feature you do:

for feature in layer.getFeatures():
    geom = feature.geometry()
    len = geom.length()

And so on...