1

I have a unique layer with different polygon features. The symbology for each one is a simple fill with a random color, except if the name of the feature starts with "UR". In this case, the color is still random but the filling must be a Line Pattern.

I have to do it for QGIS using Python but I have to admit that I am a starter in programming. I know the simple fill can be done by QgsFillSymbol.createSimple(), but how can I get the line pattern filling? I have used the QgsLinePatternFillSymbolLayer.create(), but I am sure I am missing something...

Is there a way to do it using Categorized Symbols?

Here is a little example of what I have. I know it has mistakes, but as I told you, I am just a starter and this is only the "chassis" of what I am trying to do.

if name.startswith("UR"):

    symb = QgsLinePatternFillSymbolLayer.create( { 'angle' : 30, 'distance' : 2.0, 'width' : 0.5, 'color' : color } )
    symb.setlineAngle(angle)symb.setDistance(distance)
    symb.setLineWidth(width)
    symb.setcolor(color)
else:
    symb = QgsFillSymbol.createSimple( { 'color' : color,  'outline_color' :'gray'  } )

1 Answer 1

2

One way to achieve your goal could be to use the QgsRuleBasedRenderer and to set the relevant rules. An example that combines a default plain fill symbol and a line pattern symbol is given in the following code snippet:

# Define a default symbol with a single symbol layer. 
symbol_lyr_default = QgsSimpleFillSymbolLayer()
symbol_lyr_default.setFillColor(QColor("blue"))
symbol_default = QgsFillSymbol()
symbol_default.appendSymbolLayer(symbol_lyr_default)

# Define a line pattern symbol. 
symbol_lyr_line = QgsLinePatternFillSymbolLayer()
symbol_lyr_line.setLineAngle(30)
symbol_lyr_line.setDistance(2)
symbol_lyr_line.setLineWidth(0.5)
symbol_lyr_line.setColor(QColor("orange"))
symbol_line = QgsFillSymbol()
symbol_line.deleteSymbolLayer(0)
symbol_line.appendSymbolLayer(symbol_lyr_line)

# Define a default rule that associates all features to the default symbol.
root_rule = QgsRuleBasedRenderer.Rule(symbol_default)

# Add another rule that sets the line symbol for features whose "name" attribute starts with 'UR'. Add the rule as a child of the root_rule.
s_filter = 'substr("name", 0, 2) = \'UR\''
line_rule = QgsRuleBasedRenderer.Rule(symbol_line, 0, 0, s_filter)
root_rule.appendChild(line_rule)

# Define a rule based renderer and use it to render the layer. 
rule_renderer = QgsRuleBasedRenderer(root_rule)
lyr.setRenderer(rule_renderer)
lyr.triggerRepaint()

The code above works on some sample data downloaded from the natural earth database. I hope it does also for your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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