To copy & paste features from one layer to another layer you have several options. These are two that I recommend:
OPTION A: Using iface object
- Select features in
source_layer
.
- Use
iface.copySelectionToClipboard(source_layer)
- Open the edit session in
target_layer
.
- Use
iface.pasteFromClipboard(target_layer)
- Save changes to
target_layer
.
Note that 1, 3 and 5 could be done programmatically as well, which is well covered by the PyQGIS Cookbook.
OPTION B: Using 'AppendFeaturesToLayer' plugin
The 'Append Features to Layer' is a plugin based on the QGIS copy&paste's code.
The plugin works even if your source and target layers don't share all fields (just as QGIS copy&paste does!).
How to call it from PyQGIS
After installing the plugin, use a normal processing call depending on your use case:
1. Copy all features from source layer to target layer:
params = {'SOURCE_LAYER': source_layer,
'TARGET_LAYER': target_layer,
'ACTION_ON_DUPLICATE' : 0} # 0: Just append all features
processing.run("etl_load:appendfeaturestolayer", params)
2. Only copy selected features from source layer to target layer:
params = {'SOURCE_LAYER': QgsProcessingFeatureSourceDefinition(source_layer_path,
True),
'TARGET_LAYER': target_layer,
'ACTION_ON_DUPLICATE' : 0} # 0: Just append all features
processing.run("etl_load:appendfeaturestolayer", params)
NOTE: If you're more interested in the details, you can actually read the Python code of the algorithm. The key part is to establish a mapping between source and target layers: See the code.
This is the GUI of the algorithm:
Best Answer
You could use the
setActiveLayer()
method of theQgisInterface
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: