Using the python console, I am trying to copy values from a virtual field into another non-virtual field. Both fields are integer types but I get NULL in the non-virtual field. I followed the answer in this post: Is it possible to programmatically add calculated fields?
The following code works if both fields are non-virtual but doesn't work if copying from a virtual field. Here is the code:
from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature
vl = QgsVectorLayer("C:\Users\Me\Desktop\Test\\Layer.shp", "Layer", "ogr")
vl.startEditing()
idx = vl.fieldNameIndex( 'Field_1' ) # Field_1 is the non-virtual field
e = QgsExpression( ' "Field_2" ' ) # Field_2 is the virtual field
e.prepare( vl.pendingFields() )
for f in vl.getFeatures():
f[idx] = e.evaluate( f )
vl.updateFeature( f )
vl.commitChanges()
This works manually through the Field Calculator.