[QGIS-Developer] Changing attributes of a newly created feature in Python form init code

Johannes Kröger (WhereGroup) johannes.kroeger at wheregroup.com
Wed Jan 10 01:48:24 PST 2024


Still stumped with this, now cross-posted to 
https://gis.stackexchange.com/questions/474014/changing-attributes-of-a-newly-created-feature-in-python-form-init-code

I noticed that the both the `id(feature)` is always different when I 
look at it in either function which suggests the object got copied (by 
the `partial()` call?). The same is true for `feature.id()`. As a hack I 
tried using a global instead of passing the feature to `on_ok()`. 
[insert confused emoji here]

Probably I am blind to something really basic.

Cheers, Hannes

On 04.01.24 16:47, Johannes Kröger (WhereGroup) via QGIS-Developer wrote:
>
> Hey guys,
>
> I feel really dumb and I guess I am missing some basic concept...:
>
>   * I have a layer with two attributes: "text" (string) and "int"
>     (integer).
>   * I used drag'n'drop form design to have a form with just the "text"
>     attribute in it.
>   * I added Python Init Code:
>
> ```
> from functools import partial
>
> def on_ok(layer, feature):
>     field_idx = layer.fields().indexOf("int")
>     attribute_changed = layer.changeAttributeValue(feature.id(), 
> field_idx, 12345)
>     if not attribute_changed:
>         raise Exception("Attribute value could not be changed!")
>
> def my_form_open(dialog, layer, feature):
>     ok_button = dialog.findChild(QPushButton)
>     ok_button.clicked.connect(partial(on_ok, layer, feature))
> ```
>
> So the form does not show an input widget for the "int" field. But 
> when pressing OK, the code should change the edited feature's "int" 
> value to 12345.
>
> This works if I edit existing features.
>
> But if I create a new feature, the "int" value will be empty/NULL 
> instead of 12345.
>
> Any pointers on how to properly update a new feature's attribute 
> fields, that exist on a layer but are not shown the user with the 
> QGIS' widgets in the attribute form?
>
> Cheers, Hannes
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20240110/781a5cbc/attachment.htm>


More information about the QGIS-Developer mailing list