1

I would like to ask if it's somehow possible to create script with rule-based symbology in QGIS which would be based on expressions given from separate table (for example CSV, or Excel sheet). I used code given from user eurojam:

def rule_based_style(layer, symbol, label, expression, color):
    root_rule = renderer.rootRule()
    rule = root_rule.children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color))
    root_rule.appendChild(rule)

layer = iface.activeLayer() 
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRenderer(symbol)
f1 = open("d:/test.csv", "r", encoding='utf-8', errors='ignore')
count = 1
for line in f1.readlines():
   rule_based_style(layer, symbol, str(count), line, "red")
   count = count + 1

layer.setRenderer(renderer)
layer.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(layer.id())

Problem is that my expression which is for example: "Benzinka" = 'ano' AND "typ_silnic" = 'trunk' AND "Corine" = '121' now gets another quotation marks and the result is: """Benzinka"" = 'ano' AND ""typ_silnic"" = 'trunk' AND ""Corine"" = '121'"

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
LenkaT
  • 19
  • 2

1 Answers1

3

A basic script like the one below would do the job (based on the solution posted here Adding new rule by using QgsRuleBasedRenderer to existing one in PyQGIS?). The csv file in the example below is d:/test.csv:

def rule_based_style(layer, symbol, label, expression, color):
    root_rule = renderer.rootRule()
    rule = root_rule.children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color))
    root_rule.appendChild(rule)

layer = iface.activeLayer() 
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRenderer(symbol)
f1 = open("d:/test.csv", "r", encoding='utf-8', errors='ignore')
count = 1
for line in f1.readlines():
   rule_based_style(layer, symbol, str(count), line, "red")
   count = count + 1

layer.setRenderer(renderer)
layer.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(layer.id())
eurojam
  • 10,762
  • 1
  • 13
  • 27
  • It works, but problem is, that each rule has added quotation marks there:

    """Benzinka"" = 'ano' AND ""typ_silnic"" = 'trunk' AND ""Corine"" = '121'"

    – LenkaT Feb 12 '20 at 10:12
  • in my testdata it worked...the data was like: "fclass" = 'farm' "fclass" = 'town' "fclass" = 'town' and "population" > 10000 – eurojam Feb 12 '20 at 10:27