Skip to main content
Tweeted twitter.com/StackGIS/status/1567482838299066368
Became Hot Network Question
edited tags
Link
PolyGeo
  • 65.4k
  • 29
  • 114
  • 345
Source Link
william3031
  • 381
  • 2
  • 13

PyQGIS autoincrement id field

Is there a way to autoincrement the id field on a blank layer created in PyQGIS?

For example, this is a blank layer and I want to autoincrement the fid field for anything features that are added.

from qgis.core import QgsVectorLayer, QgsFeature, QgsField, QgsGeometry, QgsPointXY, QgsField, QgsProject

vl = QgsVectorLayer("Polygon", "blank_poly", "memory")
crs = vl.crs()
crs.createFromId(28355) # or whatever
vl.setCrs(crs)
pr = vl.dataProvider()
# Enter editing mode
vl.startEditing()
# add fields
pr.addAttributes( [ QgsField("fid", QVariant.Int),
                QgsField("Label",  QVariant.String,'character', 255),
                QgsField("Source", QVariant.String),
                QgsField("Date", QVariant.Date),
                QgsField("Status", QVariant.String),
                QgsField("Theme", QVariant.String),
                QgsField("SubTheme", QVariant.String),
                QgsField("Comments", QVariant.String,'character', 255),
                QgsField("Area", QVariant.String),
                QgsField("Name", QVariant.String)] )
vl.commitChanges()
# Show in project
QgsProject.instance().addMapLayer(vl)

I have attemped this: Adding feature id column that autoincrements using PyQGIS?

from qgis.core import QgsVectorLayer, QgsFeature, QgsField, QgsGeometry, QgsPointXY, QgsField, QgsProject

vl = QgsVectorLayer("Polygon", "blank_poly", "memory")
crs = vl.crs()
crs.createFromId(28355) # or whatever
vl.setCrs(crs)
pr = vl.dataProvider()
# Enter editing mode
vl.startEditing()
# add fields
pr.addAttributes( [ QgsField("fid", QVariant.Int),
                QgsField("Label",  QVariant.String,'character', 255),
                QgsField("Source", QVariant.String),
                QgsField("Date", QVariant.Date),
                QgsField("Status", QVariant.String),
                QgsField("Theme", QVariant.String),
                QgsField("SubTheme", QVariant.String),
                QgsField("Comments", QVariant.String,'character', 255),
                QgsField("Area", QVariant.String),
                QgsField("Name", QVariant.String)] )

# sequential field id updates
pr.dataProvider().addAttributes(fields)
pr.updateFields()
                
i = 0
with edit(vl):  
    for feature in pr.getFeatures():
        feature.setAttribute(feature.fieldNameIndex('fid'), i)
        i += 1                
                
vl.commitChanges()
# Show in project
QgsProject.instance().addMapLayer(vl)

But I get these errors:

Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.7\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "", line 1, in File "", line 23, in AttributeError: 'QgsVectorDataProvider' object has no attribute 'dataProvider'

I am running on QGIS 3.22.