21

I want to create a temporary layer out of an existing layer and only get those features from the existing layer, which are selected. I know that ArcGIS has this functionality that you can create a layer from selected features.

However, I could not find any working solution for this in QGIS. I am aware of this question which describes, how to save a selection into a new file which is not my goal here.

Checking the context menu for "save as..." did not yield any results. In the plugin section with the search word "selection" did not give any meaningful results either.

While trying around I came up with a solution with PyQGIS but I would prefer one which does not involve any coding because I need to show this to a colleague.

layer = iface.activeLayer() # layer which has a selection 
feat = layer.selectedFeatures()
fields = layer.fields()

selection = QgsVectorLayer('Point', 'temp', 'memory')

dp = selection.dataProvider()
dp.addAttributes(fields)
dp.addFeatures(feat)

selection.commitChanges()
selection.updateExtents()

QgsMapLayerRegistry.instance().addMapLayer(selection)

2 Answers 2

33

I think there are at least two methods:

  1. Select your features and run the "Extract selected features" tool from the Processing Toolbox (Ctrl+Alt+T).

  2. As described in this answer to a related question:

    • Select your features
    • Copy them with either Ctrl+C or from the menu bar (Edit > Copy Features)
    • Paste the features as a temporary scratch layer with either Ctrl+Alt+V or from the menu bar (Edit > Paste Features as > Temporary Scratch Layer).
2
  • @LaughU - Most welcome! Glad it helped :)
    – Joseph
    Nov 2, 2017 at 10:25
  • 2
    In current (2020) Qgis, this tool is called Extract Selected Features
    – Llaves
    Sep 20, 2020 at 23:31
5

One can try using the materialize() method of the QgsFeatureSource class.

Note: this is available since QGIS 3.0

from qgis.utils import iface
from qgis.core import QgsProject

layer = iface.activeLayer()

temp_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds()))

QgsProject.instance().addMapLayer(temp_layer)

References:

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.