7

I am updating a QGIS Plugin from QGIS 2 to 3 and I am struggling with changing the layer symbology (a single symbol type for a line layer). I would like to have all lines in my layer to have the same color and the same thickness. For QGIS 2 it worked like this:

symbols = iface.activeLayer().rendererV2().symbols()
symbol = symbols[0]
symbol.setColor(QColor.fromRgb(0, 225, 0))
symbol.setWidth(0.75)
qgis.utils.iface.mapCanvas().refresh()
qgis.utils.iface.legendInterface().refreshLayerSymbology(iface.activeLayer())

For QGIS 3, I understood from the API break documentation that rendererV2() has been renamed to renderer(). Further, symbols() has been removed:

symbols( QgsRenderContext& context ) method should be used instead (previously available as symbols2 in PyQGIS bindings).

I find it hard to connect this information and what I find under the QgsRenderContext documentation to my problem.

An explanation on how to solve such issue based on the documentations would be helpful.

2
  • The correct answer depends on your renderer type - is this single symbol, categorized, or something else?
    – ndawson
    Commented May 25, 2018 at 0:53
  • @ndawson: a single symbol type for a line layer. I would like to have all lines in my layer to have the same color and the same thickness. I will add this info to the question. Commented May 25, 2018 at 5:39

1 Answer 1

11

If it's a single symbol renderer, then something like:

layer = iface.activeLayer()
single_symbol_renderer = layer.renderer()

symbol = single_symbol_renderer.symbol()
symbol.setColor(QColor.fromRgb(0, 225, 0))
symbol.setWidth(0.75)

# more efficient than refreshing the whole canvas, which requires a redraw of ALL layers
layer.triggerRepaint()

# update legend for layer
qgis.utils.iface.layerTreeView().refreshLayerSymbology(layer.id())
2
  • Further, a short explanation on how to solve such issue based on the documentations would be helpful. E.g. starting with the QgsVectorLayer, I see that from the classQgsVectorLayer I can retrieve with renderer() an object of the classQgsFeatureRenderer. However, there I see no function symbol() to retrieve a classQgsMarkerSymbol, which I need to then use setColor() etc. Commented May 25, 2018 at 6:52
  • 1
    You need to also check the subclasses - in this case calling renderer() on the layer will give you the subclass, a QgsSingleSymbolRenderer. Checking qgis.org/api/classQgsSingleSymbolRenderer.html shows the symbol/setSymbol methods.
    – ndawson
    Commented May 25, 2018 at 7:26

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.