我想使用PyQGIS添加一个新字段并计算每个功能的值。类似于字段计算器选项。
我的“字段计算器”表达式例如: y(start_point($geometry))
from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature
vl = iface.activeLayer()
vl.startEditing()
#step 1
myField = QgsField( 'myNewColumn', QVariant.Float )
vl.addAttribute( myField )
idx = vl.fieldNameIndex( 'myNewColumn' )
#step 2
e = QgsExpression( 'y(start_point($geometry))' )
e.prepare( vl.pendingFields() )
for f in vl.getFeatures():
f[idx] = e.evaluate( f )
vl.updateFeature( f )
vl.commitChanges()
这是我得到的错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/var/folders/0r/q6nxg6w54fv4l7c8gksb2t500000gn/T/tmp9dosIe.py", line 30, in <module>
f[idx] = e.evaluate( f )
KeyError: '-1'