0

I'd like to create a new field named "vctcn93", loop the features of active layer, if string "metro" in feature name, I'd like to add a value string "get" into the field "vctcn93".

But when I check the table, I found a field named "vctcn93" but null value in it.

enter image description here

When I check some features in console, the features got the value already.

enter image description here

These are my codes first time:

 def AddAttri():
    layer = qgis.utils.iface.activeLayer()
    pr = layer.dataProvider()
    feild = QgsField("vctcn93", QVariant.String, "text", 254)
    pr.addAttributes([feild])
    layer.updateFields()

    layer.selectAll()
    ids = layer.selectedFeatureIds()
    features = (f for f in layer.getSelectedFeatures())

    index = a.fieldNameIndex("vctcn93")

    for a in features:
        if "metro_station" in a.attribute("name"):
            a.setAttribute(index, "get")

    layer.updateFeature(a)

And I tried another way to figure it out, but failed.

Field with blank value in the table the same.

Codes second time.

def AddAttri():
    layer = qgis.utils.iface.activeLayer()
    pr = layer.dataProvider()
    feild = QgsField("vctcn93", QVariant.String, "text", 254)
    pr.addAttributes([feild])
    layer.updateFields()

    layer.selectAll()
    ids = layer.selectedFeatureIds()
    features = (f for f in layer.getSelectedFeatures())

    index = a.fieldNameIndex("vctcn93")

    for a in features:
        if "metro_station" in a.attribute("name"):
            fs = a.fields()
            fs.append(feild)
            a.setFields(fs)
            a.setAttribute(index, text)

    layer.updateFeature(a)
0

Modify

for a in features:
    if "metro_station" in a.attribute("name"):
        fs = a.fields()
        fs.append(feild)
        a.setFields(fs)
        a.setAttribute(index, text)

layer.updateFeature(a)

To

for a in features:
    if "metro_station" in a.attribute("name"):
        fs = a.fields()
        fs.append(feild)
        a.setFields(fs)
        a.setAttribute(index, text)
        layer.updateFeature(a)

This way you update every feature in the layer that satisfied your if statement and not just the last feature in features.

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.