qgis – Utilizing User Defined Variables in QGIS

qgisuser interfacevariables

In QGIS Graphical modeller there is the option to create user defined variables that one can use in the model. I dont always need to use the modeller to do stuff. Is there a way to have user defined variables in regular QGIS (very good for styling)?

I have found that in model properties I can use Title, Abstract, Author etc. for this, but that is really not very elegant. I just want regular variables that I can set and then use. Really good for visualization works.

Best Answer

Yes, you can define your own custom variables in QGIS in different levels like as in global Level, as project or layer variables and even as ad hoc variables in QGIS expressions using the function with_variable().

See functions help for with_variable() expression as well as an expample where three different variable are declared: vertex (=20), azimuth1 and azimuth2 (the last two have an expression assigned as values).

Go to the Settings / properties of the desired Level (e.g. right Click layer > properties > tab variables) and select variables to add your own variable by typing a name and the value of the variable. You can then call the variable by its Name preceded with @ - e.g. @my_variable.

See here for more information about custom variables: http://nyalldawson.net/2015/12/exploring-variables-in-qgis-pt-3-layer-level-variables/


The content (value) of the varible can be set to an attribute or a complex expression e.g. to generate all kind of sophisticated data defined styles. So this example: define a project variable called set_color with this value (string):

case 
when value = 1 then 'red' 
when value = 2 then 'blue' 
when value = 3 then 'green' 
else 'yellow' 
end

enter image description here

Now use the variable @set_color to create a data defined color of a layer, based on its attribute field value using the function eval(): eval(@set_color):

enter image description here

Variables you defined at global, project or layer level will appear in expression string builder dialog under variables:

enter image description here

Related Question