2

I am trying to create a RuleBasedRenderer with two layers. The first layer is used to fill the polygons and the other should create a hatching effect with lines. However, the code below, creates the layers needed, but both line color and fill color are the same. Do you know how can solve this?

        symbol = QgsSymbol.defaultSymbol(layer.geometryType())
        symbol.deleteSymbolLayer(0)
        symbolLayer2 = QgsSimpleFillSymbolLayer()
        symbolLayer1 = QgsLinePatternFillSymbolLayer()
        symbol.appendSymbolLayer(symbolLayer1)
        symbol.appendSymbolLayer(symbolLayer2)
        renderer = QgsRuleBasedRenderer(symbol)
        # get the "root" rule
        root_rule = renderer.rootRule()

        for label, expression, color_name in rules:
            # create a clone (i.e. a copy) of the default rule
            rule = root_rule.children()[0].clone()
            # set the label, expression and color
            rule.setLabel(label)
            rule.setFilterExpression(expression)
            if color_name == 'orange':
                print(len(rule.symbols()))
                rule.symbol().setColor(QColor(color_name))

            else: rule.symbol().setColor(QColor(color_name))
            root_rule.appendChild(rule)

        # delete the default rule
        root_rule.removeChildAt(0)

        # apply the renderer to the layer
        layer.setRenderer(renderer)
        layer.triggerRepaint()

P.S. The if statement is for testing purposes.

1

Found the solution.

    symbol = QgsSymbol.defaultSymbol(layer.geometryType())
    symbol.deleteSymbolLayer(0)
    symbolLayer2 = QgsSimpleFillSymbolLayer()
    symbolLayer1 = QgsLinePatternFillSymbolLayer()
    [+] symbol.appendSymbolLayer(symbolLayer2)
    [+] symbol.appendSymbolLayer(symbolLayer1)
    renderer = QgsRuleBasedRenderer(symbol)
    # get the "root" rule
    root_rule = renderer.rootRule()

    for label, expression, color_name in rules:
        # create a clone (i.e. a copy) of the default rule
        rule = root_rule.children()[0].clone()
        # set the label, expression and color
        rule.setLabel(label)
        rule.setFilterExpression(expression)
        if color_name == 'orange':
            [+]rule.symbol().symbolLayer(1).setColor(QColor('black'))
            [+]rule.symbol().symbolLayer(1).setDistance(3)
            rule.symbol().symbolLayer(0).setColor(QColor(color_name))

        else: rule.symbol().setColor(QColor(color_name))
        root_rule.appendChild(rule)

I just had to use the function symbolLayer to select the right layer and then set the attributes I want. I had also to change the order I append the symbol Layers. Otherwise, the line pattern would appear under the fill layer and not above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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