PyQGIS – Copying Layer Styles

copylayerspyqgisstyle

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.

Best Answer

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