1

I am starting with PyQGIS and I would like to change the values of two fields within selected features:

from qgis.PyQt.QtCore import QVariant
parent = iface.mainWindow()
mc = iface.mapCanvas()
myLyr = mc.currentLayer() #aktueller Layer, der als Quelle genutzt wird
flds =myLyr.fields()
fld1 = "BTYP" #Name of the first field
fld1i = myLyr.fields().indexOf(fld1) #get the index of the first field
fld1val = "herdamit"#Value of the first field
fld2 = "WS"
fld2i = myLyr.fields().indexOf(fld2)
fld2val = "superduber"
caps=myLyr.dataProvider().capabilities() 
myData = {fld1i: fld1val,fld2i: fld2val}
mySel = myLyr.selectedFeatures()
print(myData)
with edit(myLyr):
 if caps & QgsVectorDataProvider.ChangeAttributeValues:
 for f in mySel:
 myLyr.dataProvider().changeAttributeValues({f : myData})
 myLyr.updateFeature(f)
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Oct 15, 2019 at 18:41
2
  • What happens if you run the code, do you receive any errors or does it run and nothing happens? Are you running this from the python console or from a script? Commented Oct 16, 2019 at 9:18
  • There is no error and no result. The code is running from the python console Commented Oct 16, 2019 at 11:44

1 Answer 1

1

This code-snippet works fine

parent = iface.mainWindow()
mc = iface.mapCanvas()
myLyr = mc.currentLayer()
flds =myLyr.fields()
fld1 = "BTYP" #Name of the first field
#fld1i = myLyr.fields().indexOf(fld1) #get the index of the first field
val1 = "!urmele!"#Value of the first field
fld2 = "E3_KARTO"
#fld2i = myLyr.fields().indexOf(fld2)
val2 = "!durmele!"
caps = myLyr.dataProvider().capabilities()
for f in myLyr.selectedFeatureIds():
 #print(f)
 if caps & QgsVectorDataProvider.ChangeAttributeValues:
 attrs={flds.indexOf(fld1):val1,flds.indexOf(fld2):val2}
 myLyr.dataProvider().changeAttributeValues({ f : attrs })
answered Oct 16, 2019 at 18:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.