I'm trying to write a python function that takes a BGSREF attribute from a BGS geology shapefile and uses it to colour up the geology polygons of a shapefile.
I posted my non-code working as a part answer to Data-defined Styles in QGIS as it shows the maths behind taking a BGSREF code and converting it to RGB values, but I would like to know what needs to be corrected to have the full solution.
Using Nathan's QGIS Blog post on User defined expression functions for QGIS as a basis I created my code like:
from qgis.utils import qgsfunction
from qgis.core import QGis
aColourAdjust = [0,7,14,21,31,42,54,67,80,100]
@qgsfunction(1, "Python")
def BGSrefToQGIScolorRGB(values, feature, parent):
"""
Converts BGSref colour (attribution) to RGB values.
Output as integers in the range 0 - 255, in the style:
color_rgb(rrr,ggg,bbb) or color_rgba(rrr,ggg,bbb,aaa)
"""
# set some variables
#rgbValue = "color_rgb(255,255,255)"
rgbValue = "255,255,255"
#rgbValue = "<255>,<255>,<255>"
isTransparent = 'False'
bgsref2Convert = values[0]
# Test the length of the input value and pad with zeros if applicable.
if len(str(bgsref2Convert)) == 1:
bgsref2Convert = "00" + str(bgsref2Convert)
elif len(str(bgsref2Convert)) == 2:
bgsref2Convert = "0" + str(bgsref2Convert)
elif len(str(bgsref2Convert)) == 3:
pass
else:
isTransparent = 'True'
#Now we can calculate the RGB values...
if isTransparent:
#rgbValue = "color_rgba(255,255,255,255)"
rgbValue = "255,255,255,255"
#rgbValue = ""<255>,<255>,<255>,<255>"
else:
yellow = aColourAdjust[int(bgsref2Convert[:1])]
cyan = aColourAdjust[int(bgsref2Convert[-1:])]
magenta = aColourAdjust[int(bgsref2Convert[1:2])]
# 100.0 is deliberate to get a floating point result, otherwise the result of division will always be zero.
red = 255-((cyan/100.0)*255)
green = 255-((magenta/100.0)*255)
blue = 255-((yellow/100.0)*255)
#Now just need to find the expected QGIS format for the colour output...
#rgbValue = "color_rgb(" + str(int(red)) + "," + str(int(green)) + "," + str(int(blue)) + ")"
rgbValue = str(int(red)) + "," + str(int(green)) + "," + str(int(blue))
#rgbValue = "<" + str(int(red)) + ">,<" + str(int(green)) + ">,<" + str(int(blue)) + ">"
return rgbValue
I start QGIS (2.2.0), open the Python Console, import my function, and it shows in the expression string builder.
For my chosen layer style properties, I choose Single Symbol, data defined properties, Expression and create an expression like: BGSrefToQGIScolorRGB( "BGSREF" ) and apply this, but I never seem to get any colours in the map.
The help tip tells me the colour format is: '<red>,<green>,<blue>,<alpha>' but what does this actually mean?
I've tried outputting the results as the following strings (255 here indicates number format not the literal output):
* <255><255><255><255>
* <255><255><255>
* 255,255,255
* color_rgb(255,255,255)
Nothing seems to work for me.
What format is expected?