3

I have added a points layer in which I have to put different SVG icons, according to the column level.

So far so good, the separation is according to the level using a default symbol, but I want to change this default symbol to be an SVG symbol.

my_rules = ( ('INICIAL','regexp_match("NIVEL",\'INICIAL\')','#B18904'), ('PREESCOLAR','regexp_match("NIVEL",\'PREESCOLAR\')','#00FF40') )
symbol = QgsSymbolV2.defaultSymbol(vlayer.geometryType()) 
renderer = QgsRuleBasedRendererV2(symbol)
root_rule = renderer.rootRule()
for label,expression,color_name in my_rules:
    rule = root_rule.children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color_name))
    root_rule.appendChild(rule) 
root_rule.removeChildAt(0)          
vlayer.setRendererV2(renderer)

I am trying to create a symbol QgsSvgMarkerSymbolLayerV2, but I do not know how to use it within the rules-based symbology?

2

You could use something like the following which creates a dictionary of properties for the svg and then changes the default symbol layer using the QgsSymbol::changeSymbolLayer() method:

from PyQt4.QtGui import QColor

vlayer = iface.activeLayer()
my_rules = ( ('INICIAL','regexp_match("NIVEL",\'INICIAL\')','#B18904'), ('PREESCOLAR','regexp_match("NIVEL",\'PREESCOLAR\')','#00FF40') )

svgStyle = {}
svgStyle['name'] = 'path/to/icon.svg'
svgStyle['outline'] = '#000000'
svgStyle['size'] = '15'
symbolLayer = QgsSvgMarkerSymbolLayerV2.create(svgStyle)

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

renderer = QgsRuleBasedRendererV2(symbol)
root_rule = renderer.rootRule()
for label,expression,color_name in my_rules:
    rule = root_rule.children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color_name))
    root_rule.appendChild(rule) 

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

Example using "Arrow_01.svg":

Example

  • 1
    Thank you. I understand better how it works QgisSymbol :: changeSymbolLayer () – Marisol Prado Oct 3 '17 at 14:29
  • @MarisolPrado - Most welcome, glad it helped :) – Joseph Oct 4 '17 at 9:15

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.