[GIS] How to add multiple attributes to a newly created feature with PyQGIS

pyqgispythonqgisqt

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:

lyr = iface.activeLayer()
feat = QgsFeature()
feat.setAttributes( [0,"CAP","NUEVO","00000"] )
feat.setGeometry( QgsGeometry.fromPoint(QgsPoint(-75.32, -2) ) )
lyr.dataProvider().addFeatures( [feat] )

Regarding your code, I would say you don't need to use attr1 and attr2 but to use a single attrs, like this:

attrs = [None] * len(pr.fields())
attrs[idx1] = var1.text()
attrs[idx2] = var2.text()
Feat.setAttributes( attrs )

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.