1

I have this code to set SVG icons only for selected features. It works, but only with point geometry, while I have a layer with polygon geometry. How can I modify this code to works also with polygon geometry?

vlayer = iface.activeLayer()

svgStyle = {}
svgStyle['name'] = path
svgStyle['outline'] = '#000000'
svgStyle['size'] = '15'
symbolLayer = QgsSvgMarkerSymbolLayer.create(svgStyle)

symbol = QgsSymbol.defaultSymbol(vlayer.geometryType()) 
symbol.changeSymbolLayer(0, symbolLayer)

renderer = QgsRuleBasedRenderer(symbol)
root_rule = renderer.rootRule()
rule = root_rule.children()[0].clone()
rule.setLabel('test')
rule.setFilterExpression('is_selected()')
root_rule.appendChild(rule) 

root_rule.removeChildAt(0)
vlayer.setRenderer(renderer)

I thought that probably it's not possible to apply a SvgMarkerSymbol to a polygon layer and that I have to use before QgsCentroidFillSymbolLayer, but I don't know how.

3

You're right, QgsCentroidFillSymbolLayer is the way to go. You will have a RuleBase renderer, with the following structure

  • QgsFillSymbol [default rule (always)]
    • QgsSimpleFillSymbolLayer
  • QgsFillSymbol [is_selected() rule]
    • QgsCentroidFillSymbolLayer
      • QgsMarkerSymbol
        • QgsSvgMarkerSymbolLayer
vlayer = iface.activeLayer()

# Create SVG marker symbol
svgStyle = {
    "name": "path/to/image.svg",
    "outline": "#000000",
    "size": "15",
}
svgLayer = QgsSvgMarkerSymbolLayer.create(svgStyle)
svgSymbol = QgsMarkerSymbol()
svgSymbol.changeSymbolLayer(0, svgLayer)

# Default symbol, for unselected polygons
symbol = QgsSymbol.defaultSymbol(vlayer.geometryType())

# Centroid fill symbol for selected polygons
centroid = QgsCentroidFillSymbolLayer()
centroid.setSubSymbol(svgSymbol)
selectedSymbol = QgsFillSymbol()
selectedSymbol.changeSymbolLayer(0, centroid)

# Create renderer
renderer = QgsRuleBasedRenderer(symbol)
rule = QgsRuleBasedRenderer.Rule(
    selectedSymbol, label="Selected", filterExp="is_selected()"
)
renderer.rootRule().appendChild(rule)
vlayer.setRenderer(renderer)

1
  • I shouldn't say it, but I love you
    – Lorenzo
    Feb 18 '20 at 10:51

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.