5

I looking for solution for getting a numbering an attribute call "NAME" by clicking on polygon. I have dataset with polygon and I want to get number like 1,2,3,4... etc. I done this with simple expression in calculator, but I want to select which polygon is going to be next in numbering by clicking on it. Can I do that with some plugin on Python code?

1
  • If you have the attribute table open you can select a polygon in the map canvas, then get the selected row to be at the top of the table, and then change the attribute value for that row. Does that work? Or do you really need the value to go up automatically in case you lose count?
    – Spacedman
    Aug 3 at 18:06

1 Answer 1

4

You can achieve this using a layer action.

Right click on the layer, go to properties then actions then add a new action of type python on field and feature, and enter the following code. Make sure to use the proper field name instead of pt_id at the line fld = layer_obj.fields().lookupField('pt_id');

from qgis.core import QgsSettings
s = QgsSettings();
pt_id = s.value("last_id") or 0;
layer_id = '[%@layer_id%]';
layer_obj = QgsProject().instance().mapLayer(layer_id);
fid = [%$id%];
fld = layer_obj.fields().lookupField('pt_id');
layer_obj.changeAttributeValue(fid, fld, pt_id+1);
s.setValue("last_id",pt_id+1);

Basically, this code reads the last assigned value (or 0 for the 1st click), then adds 1 to it and save this new value in the targeted feature.

enter image description here

To use it, put the layer in edit mode, select the info tool, right click on the feature of interest and click on set id. You may have to pan the map or refresh the attribute table to see the changes.

enter image description here

PS: if you click twice on the same feature, the previous value will be overwritten.

2
  • Yeah! great! it's working! Thanks you :) Can I do some shortcut for this? For ex. I move mouse to polygon and click "ctrl+g" and set id is done? Aug 4 at 19:15
  • @AleksanderRogowski I don't know for the shortcut... feel free to ask a new question just for this!
    – JGH
    Aug 5 at 12:01

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.