Search code examples
pythonpluginsqgis

QgsVectorLayer's Attribute Table doesn't get updated when adding a new QgsFeature


When adding a new QgsFeature to a existing QgsVectorLayer feature's attributes are not added.

I want to add a new QgsFeature (polygon) to an already existing QgsVectorLayer. Feature gets added to the canvas (it is displayed on the screen) but the layer's corresponding Attribute Table doesn't get updated (newly created feature's attributes are not added)

I have read the PyQGIS Cookbook and relevant StackOverflow questions, but the code is not working and I don't know what i'm missing.

layer = self.projectInstance.mapLayersByName('draba_obcina')[0]
pr = layer.dataProvider() 
points = [QgsPointXY(0, 0), QgsPointXY(0, 1), QgsPointXY(1, 0), QgsPointXY(0, 0)]

poly = QgsFeature(layer.fields())
#if i set OGC_FID i get SQLite error: UNIQUE constraint failed (although there is no entry with OGC_FID = 3640)
#poly.setAttribute ("OGC_FID", 3640)
poly.setAttribute ("tip_spr", None)
poly.setAttribute ("id", None)
poly.setAttribute ("sif_upr", None)
poly.setAttribute ("id_upr", None)
poly.setAttribute ("vrsta_dr", None)
poly.setAttribute ("vrsta_pov", None)
poly.setAttribute ("nac_dol", None)
poly.setAttribute ("nat_dol", None)
poly.setAttribute ("usklajenost_zk", None)
poly.setAttribute ("graf_pov", None)
poly.setAttribute ("d_spr", None)
poly.setAttribute ("d_vir", None)
poly.setAttribute ("vrsta_el", None)
poly.setAttribute ("opis", "I was created by plugin")
poly.setAttribute ("createdtime", "2019-06-25 18:51:34")
poly.setAttribute ("kat", "10")

poly.setGeometry(QgsGeometry.fromPolygonXY([points]))

res, outFeats = pr.addFeatures([poly])

layer.updateExtents()
layer.commitChanges()
layer.reload() 

pr.addFeatures([poly]) returns (res == True) and the (outFeats length is 1) which to me means that adding of the feature was successful.

No errors are thrown.

But the new feature is only displayed on the canvas and no attribute is added to Attribute Table.


Solution

  • Solved my problem, the code works fine but the problem was I had to reload the Attribute Table UI for the new attributes to show in it.