Since QGIS 3.0, there is another approach available. Use the materialize() method from the QgsFeatureSource class.
Over the entire layer with the allFeatureIds() method:
# imports from qgis.utils import iface from qgis.core import QgsFeatureRequest, QgsProject # choose a layer layer = iface.activeLayer() # or with: layer = QgsMapLayerRegistryQgsProject.instance().mapLayersByName('name_of_the_layer''LAYER_NAME')[0] # create a new layer from all features new_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.allFeatureIds())) # add a new layer to the map QgsProject.instance().addMapLayer(new_layer) Over the selection of all features with the selectedFeatureIds() method from the QgsVectorLayer class:
# imports from qgis.utils import iface from qgis.core import QgsFeatureRequest, QgsProject # choose a layer layer = iface.activeLayer() # or with: # or with: layer = QgsMapLayerRegistryQgsProject.instance().mapLayersByName('name_of_the_layer''LAYER_NAME')[0] # select all features in the original layer layer.selectAll() # create a new layer from selected features new_layer = layer.materialize(QgsFeatureRequest().setFilterFids(layer.selectedFeatureIds())) # remove selection in the original layer layer.removeSelection() # add a new layer to the map QgsProject.instance().addMapLayer(new_layer) References: