7

The following two commands copy and paste layer styles of manually selected layers. Manually as in clicking on the layers you want to copy from and to.

iface.actionCopyLayerStyle().trigger()
iface.actionPasteLayerStyle().trigger()

What I would like to know is how to use these commands to copy from one specific layer to another without clicking on the first. The plan is to loop it over plenty of layers.

2 Answers 2

8

You could use the setActiveLayer() method of the QgisInterface class.

One way to set up an iterable object containing source and destination layers is to use a list of sub-lists or tuples, where the first item is the source layer (copy style from) and the second item is the destination layer (paste style too).

The example code snippet is below:

# List of layers to copy paste styles from/to
# format is [('source_layer', destination_layer)]
layers = [('points1', 'points2'),
          ('lines1', 'lines2'),
          ('polygons1', 'polygons2')]

for i in layers:
    src_lyrs = QgsProject.instance().mapLayersByName(i[0])
    if not src_lyrs:
        continue
    src = iface.setActiveLayer(src_lyrs[0])
    if src:
        iface.actionCopyLayerStyle().trigger()
        dest_lyrs = QgsProject.instance().mapLayersByName(i[1])
        if dest_lyrs:
            dest = iface.setActiveLayer(dest_lyrs[0])
            if dest and (dest_lyrs[0].geometryType() == src_lyrs[0].geometryType()):
                iface.actionPasteLayerStyle().trigger()
1
  • 1
    Grand! Works like a charm! Thanks! Nov 12, 2022 at 13:23
4

At the risk of not answering the question directly (using those commands in particular), here is an alternative solution using the QgsMapLayerStyleManager of the layer.

# get the name of the source layer's current style
style_name = source_layer.styleManager().currentStyle()

# get the style by the name
style = grid_layer.styleManager().style(style_name)

# add the style to the target layer with a custom name (in this case: 'copied')
target_layer.styleManager().addStyle('copied', style)

# set the added style as the current style
target_layer.styleManager().setCurrentStyle('copied')            

# propogate the changes to the QGIS GUI
target_layer.triggerRepaint()
target_layer.emitStyleChanged()

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.