2

I'm currently writing some code which creates a new layer from the selected features of another layer.

layer_4 = QgsProject.instance().mapLayersByName('layer_1')[0]
iface.setActiveLayer(layer_4)
layer_2 = iface.activeLayer()
selected_2 = layer_4.selectedFeatures()
crs_2 = QgsProject.instance().crs().authid()
selection = QgsVectorLayer("Point?crs=" + str(crs_2), "selection", "memory")
new_features_2 = []

for feat in selected_2:
    new_features_2.append(feat)

selection.dataProvider().addFeatures(new_features_2)
QgsProject.instance().addMapLayer(selection)

This seems to work, however the points are not displayed in the new layer and when I'm checking the attribute table it says that all elements are filtered. Why? And how do I remove the filter?

1
  • 1
    You may use new_features_2.append(QgsFeature(feat)) instead of new_features_2.append(feat) to be sure you do not share features between layers
    – ThomasG77
    Commented Mar 30, 2021 at 12:41

1 Answer 1

1

Not sure exactly why your code is not working although seen some logic issues. IMO, there is a simpler way to do the same as what you want to achieve using Processing algorithms. There is one processing algorithm named Extract selected features within Vector General in the "Processing Toolbox" panel. Using it through Python/PyQGIS, the following should do what you expect

from qgis.core import QgsProject
import processing

selectedLayer = QgsProject.instance().mapLayersByName('layer_1')[0]

if len(selectedLayer.selectedFeatures()) > 0:
    result = processing.run("native:saveselectedfeatures", {
        'INPUT': selectedLayer,
        'OUTPUT':'TEMPORARY_OUTPUT'
    })
    QgsProject.instance().addMapLayer(result['OUTPUT'])
    # If you want to unselect, uncomment below
    # selectedLayer.removeSelection()
else:
    print("No selected features for the layer")

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.