[Qgis-user] pyQGIS - set attributes by expression
Wouter Impens
wouter.impens at gmail.com
Thu Feb 7 05:19:30 PST 2019
Thanks for the help Nyall, but I still don't get any result.
I'll put the whole script here, maybe I'm doing something wrong on another
level (I'm rather new in coding):
from PyQt5.QtCore import *
from qgis.core import *
canvas = qgis.utils.iface.mapCanvas()
my_layers = canvas.layers()
for a_layer in my_layers:
a_layer.startEditing()
a_layer.addAttribute (QgsField('perc_nr', QVariant.String))
a_layer.commitChanges()
my_features = a_layer.getFeatures()
an_expr = QgsExpression('''to_string( to_int( substr( "CAPAKEY" , 7,
4)))+' ' + CASE WHEN substr( "CAPAKEY" , 14, 1) = '_' THEN '' else
lower(substr( "CAPAKEY" , 14, 1)) END + ' ' + CASE WHEN to_int( substr(
"CAPAKEY" , 15, 3)) = '0' THEN '' else to_string( to_int( substr(
"CAPAKEY" , 15, 3))) END + ' ' + CASE WHEN to_int( substr( "CAPAKEY" ,
12, 2)) = '0' THEN '' else '/' + to_string( to_int( substr( "CAPAKEY" ,
12, 2))) END''')
context = QgsExpressionContext()
for a_feat in my_features:
my_index = a_feat.fieldNameIndex('perc_nr')
context.setFeature(a_feat)
value = an_expr.evaluate(context)
a_feat.setAttribute(my_index, value)
a_layer.commitChanges()
The first part - ading the attribute - works fine, but filling in the
fields don't give any result (nor an error either).
I'm working in QGIS 3.
Thanks!
Wouter
Op do 7 feb. 2019 om 08:08 schreef Nyall Dawson <nyall.dawson at gmail.com>:
> On Wed, 6 Feb 2019 at 18:14, Wouter Impens <wouter.impens at gmail.com>
> wrote:
> >> > I'm trying to iterate over the fields of a vector layer (using the
> index) and fill in the values by an expression
> >> >
> >> > my_features = a_layer.getFeatures()
> >> > for a_feat in my_features:
> >> > mijn_index = a_feat.fieldNameIndex('perc_nr')
> >> > value = an_expr
>
> Change this to:
>
> my_features = a_layer.getFeatures()
> context = QgsExpressionContext()
> for a_feat in my_features:
> mijn_index = a_feat.fieldNameIndex('perc_nr')
> context.setFeature(a_feat)
> value = an_expr.evalute(context)
> ...
>
> Nyall
>
>
> >>
> >> What's "an_expr" here? Is it a QgsExpression object?
> >>
> >> Nyall
> >>
> >> > a_feat.setAttribute(mijn_index, value)
> >> >
> >> > a_layer.commitChanges()
> >> >
> >> > I don't get an error but nothing is filled in. I evaluated the
> expression and it's true. It also works in the field calculator.
> >> >
> >> > Anyone an idea?
> >> >
> >> >
> >> > Kind regards
> >> > Wouter
> >> > _______________________________________________
> >> > Qgis-user mailing list
> >> > Qgis-user at lists.osgeo.org
> >> > List info: https://lists.osgeo.org/mailman/listinfo/qgis-user
> >> > Unsubscribe: https://lists.osgeo.org/mailman/listinfo/qgis-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20190207/65bba236/attachment.html>
More information about the Qgis-user
mailing list