I'm trying to change a vector layer's style by changing the renderer (from QgsRuleBasedRenderer
to QgsCategorizedSymbolRenderer
), render an image, and undo the change afterwards:
layer = self.get_layer('branch')
old_renderer = layer.renderer()
unique_values = layer.uniqueValues(layer.fields().indexFromName('line_id'))
colors = ['#fa4b3c', '#d900ff', '#a72605', '#879695', '#1fbc00', '#000dff', '#ea75ff', '#fffb00', '#3a7e31', '#ffa560', '#49b9ff', '#00ffb3', ]
categories = []
for unique_value, color in zip(unique_values, colors):
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
symbol.setColor(QColor(color))
symbol.setWidth(1.25)
category = QgsRendererCategory(unique_value, symbol, str(unique_value))
categories.append(category)
layer.setRenderer(QgsCategorizedSymbolRenderer('line_id', categories))
layer.triggerRepaint()
def finished(path=path):
img = render.renderedImage()
img.save("/Users/myuser/render.png", "png")
render.finished.connect(finished)
render.start()
loop = QEventLoop()
render.finished.connect(loop.quit)
loop.exec_()
if old_renderer is not None:
# layer.setRenderer(old_renderer)
layer.triggerRepaint()
The above works, but does not undo the change in renderer at the end. If I uncomment the
layer.setRenderer(old_renderer)
it crashes the whole app instantaneously.
How do I reapply the old renderer?
old_renderer = layer.renderer().clone()
? FYI if you launch QGIS in a terminal, you might get some information upon crashing.old_renderer = layer.renderer().clone()
should work, same reason as gis.stackexchange.com/a/452791/144074clone()
, thanks! Answer it so I can accept the answer.