TransWikia.com

How to create a geometry generator symbol using PyQGIS

Geographic Information Systems Asked on August 15, 2021

I am trying to use PyQGIS to convert a Fill Symbol Layer into a geometry generator Symbol Layer in a rule-based renderer with 300 rules.

I am able to iterate over the rules and return each rule’s symbol and then the respective (unique) Symbol Layer. I know there’s a changeSymbolLayer()

What I am failing to do, is to create a QgsGeometryGeneratorSymbolLayer to overwrite the existing symbol layer. Until now, the code is something like this:

layer = iface.mapCanvas().currentLayer()
rules = layer.renderer().rootRule().children()

for rule in rules:
    label = rule.label()
    symbol_layer = rule.symbol().symbolLayer(0)
    print(symbol_layer)
    color = symbol_layer.color()
    generator = QgsGeometryGeneratorSymbolLayer()
    generator.setFillColor(color)
    generator.setGeometryExpression(expression)
    rule.symbol().changeSymbolLayer(0,generator)

In this case the QgsGeometryGeneratorSymbolLayer() fails by saying that I am not able to instantiate.

I am not understanding how to create the new symbol to apply on each rule.

One Answer

Seems like the only way to create an empty QgsGeometryGeneratorSymbolLayer is by using:

QgsGeometryGeneratorSymbolLayer.create({})

So changing just that should make the rest of the code work:

layer = iface.mapCanvas().currentLayer()
rules = layer.renderer().rootRule().children()

for rule in rules:
    label = rule.label()
    symbol_layer = rule.symbol().symbolLayer(0)
    print(symbol_layer)
    color = symbol_layer.color()
    generator = QgsGeometryGeneratorSymbolLayer.create({})
    generator.setFillColor(color)
    generator.setGeometryExpression(expression)
    rule.symbol().changeSymbolLayer(0,generator)

Correct answer by Dror Bogin on August 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP