I have a line shapefile in QGIS with several columns and the values for many of those columns could be automatically calculated and updated depending on certain other fiels.
Now, I came across the default value option in the layer properties and I tried to build a Python function that automatically generates the value, but for some reason I do not manage to automatically get the value from the field that will serve as the argument for the function.
So, after saving the function, I try the expression
defaultPrice("Type")
I just get an error, although this is how I would usually apply functions when I manually update a field (like lower("Type")
or whatever).
So, I have the field "Type"
which has the values Gardentrench
, Asphalt
, Brick Pavement
, As Built
, HDD
, Crossing and Grass
. I have another field "PricePerMe"
where I assign the cost of the "Type"
per Meter. Not even calculated, just the price per one meter.
This is the code that I wrote:
from qgis.core import *
from qgis.gui import *
@qgsfunction(args='auto', group='Custom')
def defaultPrice(Type, feature, parent):
if Type == 'Gardentrench':
price = 12.5
elif Type == 'Grass':
price = 15
elif Type == 'As Built':
price = 1
elif Type == 'Asphalt':
price = 30
elif Type == 'Brick Pavement':
price = 100
elif Type == 'HDD':
price = 250
elif Type == 'Crossing':
price = 90
else:
price = 0
return price
In the expression field, I would like to trigger this function by
defaultPrice("Type")
and update this value. In the attribute table when I update a field value or values of a column, it does display me down a correct preview value, but after running it, there are no changes in the "Type"
column:
In the default value expression editor I get this:
What am I doing wrong?
Looked at some examples that I found, but couldn't really apply any of them to my problem, although I am sure it's very trivial.
Edit: Quick note: I know how to use virtual fields and that would do also, but they are not saved in the shapefile, only in the project file and I would like to learn something new.
type
instead ofType
.