Key error when trying to add a new attribute value to feature - PyQGIS3
A warning in updateFeature()
documentation:
This method needs to query the underlying data provider to fetch the feature with matching
QgsFeature.id()
on every call.
Try in this way:
v_layer.startEditing()
iterator = v_layer.getFeatures()
seg = next(iterator)
seg["FieldOne"] = "fieldone"
seg["FieldTwo"] = "fieldtwo"
v_layer.updateFeature(seg)
v_layer.commitChanges()
or in this way for all features:
v_layer.startEditing()
for seg in v_layer.getFeatures():
seg["FieldOne"] = "fieldone"
seg["FieldTwo"] = "fieldtwo"
v_layer.updateFeature(seg)
v_layer.commitChanges()
EDIT: If you want to set the values ("fieldone","fieldtwo") only for the feature that you just created, you have to set fields for new QgsFeature
object using setFields()
method.
def createNewFeature(fieldone, fieldtwo):
seg = QgsFeature()
# set fields for new object
seg.setFields(v_layer.fields())
# set attribute values for fields
seg['FieldOne'] = fieldone
seg['FieldTwo'] = fieldtwo
# set geometry. change start and end points
seg.setGeometry(QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(2, 2)]))
# add new feature to the layer
pr.addFeatures([seg])
v_layer = QgsVectorLayer('LineString?crs=epsg:4326', 'layerName', 'memory')
pr = v_layer.dataProvider()
pr.addAttributes([QgsField('FieldOne', QVariant.String)])
pr.addAttributes([QgsField('FieldTwo', QVariant.String)])
v_layer.updateFields()
QgsProject.instance().addMapLayers([v_layer])
createNewFeature("field one", "field two")
You can use the setAttributes function:
v_layer = QgsVectorLayer('LineString?crs=epsg:4326', 'layerName2', 'memory')
pr = v_layer.dataProvider()
pr.addAttributes([QgsField('FieldOne', QVariant.String)])
pr.addAttributes([QgsField('FieldTwo', QVariant.String)])
v_layer.updateFields()
QgsProject.instance().addMapLayers([v_layer])
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([QgsPoint(10,10),QgsPoint(11,11)]))
seg.setAttributes(["a","b"])
pr.addFeatures([seg])
You just set the attributes with the coordinates as you create the feature.