I am creating a form for updating the attribute values of the newly created feature. But when i am updating the values only one attribute field is getting updated. So if i want to update the multiple attributes values of the feature how can i do that? Following is the code which i have created:
var1= None
var2= None
Dialog = None
def formOpen(dialog,layer,feat,listFields):
global myDialog, myLayer, myFeat, var1, var2
Dialog = dialog
layer = layer
Feat = feat
var1= dialog.findChild(QLineEdit,"blockId")
var2= dialog.findChild(QLineEdit,"lineEdit_2")
buttonBox = dialog.findChild(QDialogButtonBox,"buttonBox")
buttonBox.accepted.connect(validate)
buttonBox.rejected.connect(Dialog.reject)
def validate():
if len(str(var1.text())) > 0 and len(str(var2.text())) > 0 :
pr = layer.dataProvider()
idx1 = pr.fieldNameIndex("name")
idx2 = pr.fieldNameIndex("city")
print idx1, idx2
attr1 = [None] * len(pr.fields())
attr2 = [None] * len(pr.fields())
attr1[idx1] = var1.text()
attr2[idx2] = var2.text()
layer.startEditing()
Feat.setAttributes(attr1)
Feat.setAttributes(attr2)
pr.addFeatures([Feat])
layer.commitChanges()
qgis.utils.iface.mapCanvas().refresh()
Best Answer
You can use a single call to
setAttributes()
in order to set all attribute values for a feature, i.e., no need to call it twice for the same feature.For instance, the following code sets 4 attribute values of a single feature at once:
Regarding your code, I would say you don't need to use
attr1
andattr2
but to use a singleattrs
, like this:Additionally, I don't think you need to open an edit session for adding a feature. In the first code snippet of this answer, I don't start an edit session, and still the feature is added to my layer.