QGIS – Adding Many Columns to Multiple Layers

fields-attributespyqgis

The label toolbar uses fields in the attribute table of vector layers to fine tune labeling (Data defined labeling). That's the main reason i'm looking for that, but it may have more applications.

I'd like to automatically add some format columns instead of adding them manually every time.

Do you know a plugin or a way to do this manipulation automatically on multiples layers ?

I tried to get the QGIS tool "Add a field to attribute table" into a quick model which works properly, but it creates a new memory layer. And I'd like just new fields.

##Add_ETIKT_Field=name
##myvlayer=vector
##myvlayer=output vector
outputs_QGISADDFIELDTOATTRIBUTESTABLE_2=processing.runalg('qgis:addfieldtoattributestable', myvlayer,'ETIKT_Y',1,15.0,4.0,None)
outputs_QGISADDFIELDTOATTRIBUTESTABLE_1=processing.runalg('qgis:addfieldtoattributestable', outputs_QGISADDFIELDTOATTRIBUTESTABLE_2['OUTPUT_LAYER'],'ETIKT_X',1,15.0,5.0,myvlayer)

What I'm looking to automate is :

  • Open the attribute table
  • Edit button
  • Field Calculator button
  • Add Column + Type + length + Precision

It seems there's some ideas in QGIS manual, but I'd love to avoid coding anything, or at least at minimum go through the modeler.

Adding and Removing Fields

To add fields (attributes), you need to
specify a list of field definitions. For deletion of fields just
provide a list of field indexes.

if caps & QgsVectorDataProvider.AddAttributes:
    res = layer.dataProvider().addAttributes([QgsField("mytext", QVariant.String), QgsField("myint", QVariant.Int)])

if caps & QgsVectorDataProvider.DeleteAttributes:
    res = layer.dataProvider().deleteAttributes([0])

Best Answer

Within the graphical modeler (processing > grapical modeler) add 'vector layer' as input. There you can choose if it has to be a point-, line- or polygonlayer or that it does not mather (=any)

Choose 'add field to attribute table' as many times as you need extra fields. In the last algorithm you add a description under 'Added OutputVector'.

enter image description here

Here you can set the fieldname, type, length and precision.

Once you added all fields with their corresponding properties give your model a name and set a group. Save it. You'll find it under C:\Users\username.qgis2\processing\models.

Once saved, the model shows up in the processing toolbox under 'Models'. Doubleclick it to open the dialogue. In the top right corner you can select 'Run as batch process'.

enter image description here

A new dialogue appears where you can select all the layers you want to add new fields. You have to give them a new name and location to save them as a shapefile (else they would appear as a temporary layer in your project)

enter image description here