3

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()
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.