4

I have the following PyQGIS script with QGIS 3 that tries to ask for a layer, add a new field in that layer and modify the value of this field. But the code doesn't work. I get either Seems there is no valid script in the file when I use layer = QgsVectorLayer(Layer) or AttributeError: 'NoneType' object has no attribute 'isValid' when I use QgsProcessingUtils.mapLayerFromString :

##Layer=vector
context = QgsProcessingContext()
layer= QgsProcessingUtils.mapLayerFromString(Layer, context)
layer.startEditing()
if layer.dataProvider().fieldNameIndex("new_col_name") == -1:
 layer.dataProvider().addAttributes([QgsField("new_col_name", QVariant.String)])
layer.updateFields()
id_new_col= feuilles.dataProvider().fieldNameIndex("new_col_name")
for feature in layer.getFeatures():
 column_value= feature["column"]
 ... some operations ...
 layer.changeAttributeValue(feature.id(), id_new_col, new_column_value)
layer.commitChanges()
PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Jan 10, 2019 at 14:44
1

1 Answer 1

7

Not sure how to prompt for a layer, but working code below (with a shapefile) uses the currently selected layer. Note that the new field name was shortened due to name length constraints on shapefiles.

layer = iface.mapCanvas().currentLayer()
layer.startEditing()
if layer.dataProvider().fieldNameIndex("new_col_na") == -1:
 layer.dataProvider().addAttributes([QgsField("new_col_na", QVariant.String)])
 layer.updateFields()
id_new_col= layer.dataProvider().fieldNameIndex("new_col_na")
for feature in layer.getFeatures():
 layer.changeAttributeValue(feature.id(), id_new_col, "val")
layer.commitChanges()
answered Jan 16, 2019 at 15:15
1
  • If I want to add a specific column to selected layers only in Qgis? Commented Jul 21, 2022 at 12:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.