1

I have around 50 layers, which are going to have exactly the same column names and their content.

I found a way how to create the new columns in a batch way, which is presented here:

gis.stackexchange.com/questions/344779/applying-field-calculator-for-multiple-layers-at-once

but the Python code doesn't include the content, which would go inside of the newly created column.

I would like to pick the layer name up and put it into the table field, like shown here:

Is there a way to label a layer using its file name or layer name?

so my code was looking like this:

  project_layers = QgsProject.instance().mapLayers().values()


 for layer in project_layers :
  layer.startEditing()
  layer.dataProvider().addAttributes([QgsField("area", QVariant.Double)])
  layer.updateFields()


   for feature in layer.getFeatures():
    area = "layer_property( @layer_id, 'name')"
    feature.setAttributes([area])
    layer.updateFeature(feature)


    layer.commitChanges()

but it throws error.

How can I provide the content to the newly created column?

0

1 Answer 1

2

A couple of things.

  • You are trying to update a QVariant.Double field with a string
  • The string you use is just that, a string of an expression which is not evaluated and does not get the layer name
  • Some confusion with field names. You talk of layer name but the field is called area

changeAttributeValue can be used to update a feature's attributes. It takes the feature id, the field index to change, and the new value:

project_layers = QgsProject.instance().mapLayers().values()

for layer in project_layers :
    layer.startEditing()

    new_field_name = 'layer_name'
    
    # changed QVariant to String to accept the layer name
    layer.dataProvider().addAttributes([QgsField(new_field_name, QVariant.String)])
    layer.updateFields()
    
    # get the field index of the new field
    fields = layer.fields()
    idx = fields.indexFromName(new_field_name)

    for feature in layer.getFeatures():
        # area = "layer_property( @layer_id, 'name')"   this is just a string literal, it is not getting the layer name
        
        # get layer name
        name = layer.name()
        
        # update the feature attribute at the index of the new field
        layer.changeAttributeValue(feature.id(), idx, name)

    layer.commitChanges()

Your Answer

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

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