Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

In the Memory provider described in PyQGIS Cookbook or in question How to create a new empty vector layer programmatically? I can see how to create a vector layer programmatically using standard fields (String, Int, Double).

with PyQGIS/QGIS 1.8.0, is it possible to programmatically add calculated fields like the ones defined using the GUI field calculator? After some reading about QgsExpression I'm thinking in something like this:

exp = QgsExpression('Column * 3')
pr.addAttributes( [ QgsField( "fieldName", QVariant.Expression, exp ) ] )
share|improve this question
    
Is you question about adding the attribute, modifying the value of an attribute or about the expression syntax/parser present in the field calculator? Could you outline a short example of what you want to accomplish? –  Matthias Kuhn Apr 22 '13 at 15:38
    
Is about adding a new attribute defined with the parser present in the field calculator. I've edited the question to add an example that tries to clarify what I want to achieve. –  rpet May 1 '13 at 14:57
add comment

1 Answer 1

To accomplish this, you have to take a two-step approach. The first step is to create the field, the second one is to loop over all your features, evaluate the expression and update the attribute for each feature.

vl is your QgsVectorLayer

QGIS 1.8

from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature

vl.startEditing()

#step 1
myField = QgsField( 'myattr', QVariant.Int )
vl.addAttribute( myField )
idx = vl.fieldNameIndex( 'myattr' )

#step 2
e = QgsExpression( 'Column * 3' )
e.prepare( vl.pendingFields() )

f = QgsFeature()
vl.select( vl.pendingAllAttributesList() )
while vl.nextFeature( f ):
    vl.changeAttributeValue( f.id(), idx, e.evaluate( f ) )

vl.commitChanges()

QGIS 2.0

from PyQt4.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature

vl.startEditing()

#step 1
myField = QgsField( 'myattr', QVariant.Int )
vl.addAttribute( myField )
idx = vl.fieldNameIndex( 'myattr' )

#step 2
e = QgsExpression( 'Column * 3' )
e.prepare( vl.pendingFields() )

for f in vl.getFeatures():
    f[idx] = e.evaluate( f )
    vl.updateFeature( f )

vl.commitChanges()
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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