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
-
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?Joseph– Joseph2019年10月16日 09:18:36 +00:00Commented Oct 16, 2019 at 9:18
-
There is no error and no result. The code is running from the python consoleklaus k.– klaus k.2019年10月16日 11:44:07 +00:00Commented Oct 16, 2019 at 11:44
1 Answer 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 })