4

I'm trying to created a Geometry Generator symbol layer (point) that creates centroids from myLayer, a polygon map layer. Sounds easy, right? Here is my code - I think I'm missing a line to declare that I want this symbol layer to have a point geometry, and possibly much more!

Here is my code so far - please let me know what I'm missing (or where I can find a resource to explain how I can build this code).

layerName = 'myLayer'
vLayer = QgsProject.instance().mapLayersByName(layerName)[0]

generator = QgsGeometryGeneratorSymbolLayer.create({})
generator.setColor(QColor("blue"))
expression = 'centroid($geometry)'
generator.setGeometryExpression(expression)
symbol = QgsSymbol.defaultSymbol(vLayer.geometryType())
generator.setSymbolType(symbol)
print("Done.") 

1 Answer 1

7

You can try the snippet below. It works for me on a polygon layer styled with an existing simple fill symbol.

layerName = 'myLayer'
vLayer = QgsProject.instance().mapLayersByName(layerName)[0]
ggsl = QgsGeometryGeneratorSymbolLayer.create({})
ggsl.setSymbolType(QgsSymbol.Marker)
ggsl.setGeometryExpression("centroid($geometry)")
ggsl.setColor(QColor('Blue'))
symbol = vLayer.renderer().symbols(QgsRenderContext())[0]
symbol.insertSymbolLayer(1, ggsl)
vLayer.triggerRepaint()

Result:

enter image description here

The insertSymbolLayer() method of the QgsSymbolClass takes 2 arguments- the index of the position at which the symbol layer should be inserted and a the symbol layer object to insert.

Quote from the docs:

Parameters

index The index at which the layer should be added

layer The symbol layer to add

2
  • 1
    Excellent! Thanks! What is the integer in the first argument for symbol.insertSymbolLayer() - is that the layer order?
    – grego
    Nov 26, 2021 at 21:09
  • 1
    @grego, sorry for the delayed reply. Yes, the integer argument is the index at which to insert the symbol layer. I have updated my answer with a link to the docs.
    – Ben W
    Dec 2, 2021 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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