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 = QgsFillSymbol.createSimple( { 'color' : color,  'outline_color' :'gray'  } )

1 Answer 1


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_default = QgsFillSymbol()

# Define a line pattern symbol. 
symbol_lyr_line = QgsLinePatternFillSymbolLayer()
symbol_line = QgsFillSymbol()

# 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)

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

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 you have read our privacy policy.

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