I am using QGIS 3.4.x and i need change attribute value, by order selection, for example:

I have 5 polygons,

| Order of selection   | Number     |  
| Polygon 1............| set to 1...|  
| Polygon 4............| set to 2...|  
| Polygon 3............| set to 3...|  

Here is my code:

capaA = iface.activeLayer()
features = capaA.selectedFeatures()
contador = 1
capaA.changeAttributeValue(f.id(), 5, contador)
  • 1
    Is it a question ? – snaileater Jul 25 at 6:37

If I correctly understand what you are trying to do... I would do something like this:

Create a class which takes a layer in its constructor, listens for the selectionChanged signal, and connects to a method which catches the id of the selected feature. Then checks to see if a feature has actually been selected, and manages a counter (the selection order). It then looks up the index of the field you wish to fill with the selection order number (in the code below, I have an integer field called 'NUMBER', you can change to match your field name) and changes the attribute value accordingly.

You need to create an instance of this class, passing a layer object to its constructor (in the example below I just used the active layer). If doing this make sure you select the correct layer before running the code.

class update_field_by_selection_order():

    def __init__(self, layer):
        self._layer = layer
        self.counter = 0

    def feat_selected(self, fids):
        if not fids:
            self.counter = self.counter
            self.counter = self.counter + 1
            if self.counter == int(self._layer.featureCount()) or self.counter > int(self._layer.featureCount()):
                fld_idx = self._layer.fields().lookupField('NUMBER')
                atts = {fld_idx: self.counter}
                self._layer.dataProvider().changeAttributeValues({fids[0]: atts})

    def clean_up(self):

_Tool = update_field_by_selection_order(iface.activeLayer())

Once you run the code, you can just click through each feature in your layer, and the attribute field will be filled with the order in which you selected them.

I added a check which disconnects the slot from the signal when the counter reaches the number of features in the layer. It is just a quick implementation so there is no logic to detect if you select the same feature more than once, but hopefully you will get the idea.

If you wish to disconnect the slot from the signal manually, just type: _Tool.clean_up() at the prompt in the python console (outlined in red below), and hit enter.

enter image description here

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.