2

I'm trying to develop a plugin in QGIS 3.0, and I'm stuck.

A major component of my plugin is the ability to append a list of composite values as a new column to the vector layer of focus.

How do I add the values from a list to a specific column in a layer, with PYQGIS?

I've tried the following, but the column came back as empty.

    # List In Focus
    composite_list = [1,2,3,4,5,6,7,8,9,10]

    # Reference The Vector Layer In Focus
    lyrOutput = QgsVectorLayer(file_path, name + "_", "ogr")
    provider = lyrOutput.dataProvider()

    # Add A new Column To The Vector File
    provider.addAttributes([QgsField("Composite", QVariant.Double)])
    lyrOutput.updateFields()

    # Add Data To Composite Field
    comp_index = lyrOutput.fieldNameIndex('Composite')
    idx = comp_index
    lyrOutput.startEditing()

    for comp in lyrOutput.getFeature():
        lyrOutput.changeAttributeValue(comp.id(), idx, composite_list[0])
    lyrOutput.commitChanges()
1

Edited your code slightly from when you want to add data to the composite field:

  • Used the edit method which combines startEditing() and commitChanges() into a single loop.
  • Added the i parameter to iterate through the list with each feature.
  • Added a try method just in case there is a situation where the number of values in your list does not match the number of features, otherwise there will be an indexError. If this occurs, the feature will take the last value in the list.

Here is the code:

# List In Focus
composite_list = [1,2,3,4,5,6,7,8,9,10]

# Reference The Vector Layer In Focus
lyrOutput = QgsVectorLayer(file_path, name + "_", "ogr")
provider = lyrOutput.dataProvider()

# Add A new Column To The Vector File
provider.addAttributes([QgsField("Composite", QVariant.Double)])
lyrOutput.updateFields()

# Add Data To Composite Field
with edit(lyrOutput):
    for feature in lyrOutput.getFeatures():
        try:
            feature.setAttribute('Composite', composite_list[i])
            i += 1
            lyrOutput.updateFeature(feature)
        except IndexError:
            feature.setAttribute('Composite', composite_list[-1])
            lyrOutput.updateFeature(feature)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.