I am new using python in QGIS. I was trying to create a simple plugin in QGIS to create a new shapefile with a single attribute 'id'
, start the edition mode, and add new features manually on the canvas.
shp_output_path = 'C:/test/P8_100.shp'
layerFields = QgsFields()
writer = QgsVectorFileWriter(shp_output_path, 'UTF-8', layerFields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem('EPSG:25830'), 'ESRI Shapefile')
editlayer = QgsVectorLayer(shp_output_path, 'P8_100', "ogr")
layer_provider = editlayer.dataProvider()
layer_provider.addAttributes([QgsField('id', QVariant.Int)])
editlayer.updateFields()
del(editlayer)
#I reload the layer, otherwise I could not add new features
editlayer = QgsVectorLayer(shp_output_path, 'P8_100', "ogr")
QgsProject.instance().addMapLayer(editlayer)
editlayer.startEditing()
iface.actionAddFeature().trigger()
So, when I click on the canvas the usual window to insert the id value pops up. I insert a value. After inserting all the values, and before saving changes, I open the attribute table, and I see that the values inserted appear in the id attribute of the attribute table. However, if I save the changes, these values automatically change to NULL
.
This does not happen when I launch this code from the python console of QGIS. It happens when the code is launched as a plugin.
I would like that the id
values inserted in the pop-up window are inserted in the attribute table after saving changes manually or using commitChanges()
command.