Is there anyway to add the feature id column which increases automatically in attribute table programmatically? Here is a code to add a column:

fields = []
fields.append(QgsField('SOIL_ID', QVariant.Double))

But I want to add a column whose name is 'id' and it should increase in order without my touch.

  • I edit my question. There is the code to add the column. But I want to describe type for instance 'autoincrease' not 'double' or 'int'. Feb 5, 2018 at 6:27

1 Answer 1


If you just want to create a new field with incrementing values, you could try using the following:

vLayer = iface.activeLayer()

fields = []
fields.append(QgsField('ID', QVariant.Double))

i = 0
with edit(vLayer):  
    for feature in vLayer.getFeatures():
        feature.setAttribute(feature.fieldNameIndex('ID'), i)
        i += 1

This worked in a previous 2.99 version I had installed. I just updated a few minutes ago and there is now an error when trying to open the Python Console - Bug report posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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