PyQGIS – How to Copy QGIS Layer Style from One Layer to Another with PyQGIS

pyqgisstyle

I have a Layer named A with a Style which isnt saved in a .qml-File.
I want to do something with the layer e.g. compute some columns with the field calculator in a QGIS Model, also Layer A would be deleted within this process, because i just need the new one. The output is a new Layer named B.
Layer B gets a automatically a new, mostly ugly, Style. Now I want to copy the Style from Layer A to Layer B with PyQGIS.

I know I can save the layer Style of A to a .qml-File and load it for Layer B. But i would love a solution like:

style = layer_A.getStyle()
layer_B.setStyle(style)

Is there a possibility to do this?

Best Answer

I guess there must be some easier method to do it. But so far I could only figure out doing so using QgsMapLayer.styleManager() as descibed at QgsMapLayerStyleManager()

layerA = QgsProject.instance().mapLayersByName('layerA')[0]
layerB = QgsProject.instance().mapLayersByName('layerB')[0]

# get the name of the current style
style_a_name = layerA.styleManager().currentStyle()
# then get the style by the style's name
style_a = layerA.styleManager().style(style_a_name)
# Seems like you cannot simply override a style, so lets delete our style first if it exists
if 'mystyle' in layerB.styleManager().styles():
    layerB.styleManager().removeStyle('mystyle')
# Then add the style to the second layer
layerB.styleManager().addStyle('mystyle', style_a)
# Then set the just added new style as the current style
layerB.styleManager().setCurrentStyle('mystyle')
# Repaint the layer so you see the new style
layerB.triggerRepaint()
Related Question