[Python] Copy Paste Vector Attributes and Features between layers in QGIS

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to QGIS, but I was given a task to create a Python plugin for it. So to complete my task, I need to make a temporarily copy of a layer inside the algorithm, but based on what I found online, it seems like the temporary layer doesn't want to copy any features or attributes from the original layer.

    I tried to implement the code as it follows :

    #rest of the code

    #Original layer
    original_layer = QgsVectorLayer(input_file_path, "Original Layer", "ogr")
    #Add the temporary layer to the project
    temp_layer = QgsVectorLayer("LineString", "Output_layer", "memory")

    QgsProject.instance().addMapLayer(temp_layer)

    #Copy features and attributes
    features = []
    attributes = []

    for feature in original_layer.getFeatures():
    attribute = feature.attributes()
    attributes.append(attribute)
    features.append(feature)

    temp_layer.startEditing()
    data_provider = temp_layer.dataProvider()
    data_provider.addAttributes(attributes)
    data_provider.addFeatures(features)
    temp_layer.commitChanges()

    #rest of the code

    Continue reading...

Compartilhe esta Página