TransWikia.com

Changing layer symbology in QGIS 3 with QgsFeatureRendererV2

Geographic Information Systems Asked on March 18, 2021

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.

One Answer

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())

Correct answer by ndawson on March 18, 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