1

In a QGIS 2.18 plugin, I'm trying to create new features in an existing vector layer and I want to display the attribute form so the user can fill the attributes data.

The geometry is build before by parsing datas coming from websockets. Using layer.addFeature() works well for layers that does not have any fields constraints (eg: primary key).

As I need to write in Postgres/Postgis table with PK constraint, I want to use Feature Form to let the user fill attribute value and PK will handle by QGIS with default value. This way I also benefit from the settings that the user may have do for the layer fields (eg : combobox, default value, constraints, ...)

For that I'd like to use the openFeatureForm method of iface with my layer and my new feature like that:

feat = QgsFeature()
new_geom = QgsGeometry()# here I construct a geometry
feat.setGeometry(new_geom)
iface.openFeatureForm(self.layer, feat)

The attribute form show up as expected but when I hit the Ok button QGIS crash with segfault (core dumped) ...

Steps to reproduce in python console:

  • Select an editable vector layer
  • run this code snippet in QGIS python console

    layer = iface.activeLayer() feat = QgsFeature() iface.openFeatureForm(layer, feat)

  • dialog show up!

  • click OK button --> Boom! QGIS crash with segfault

I guess something is wrong in passing feature to the form but i can't figure out how to make it works...

for the moment I'm using QGIS 2.18, it's planned to upgrade to QGIS 3.X but for now, I'm looking for a QGIS 2.X solution.

1

I finally find the solution!

The feature that is used to open the feature form needs to have the same fields as the layer

So this way, it works smoothly:

feat = QgsFeature()
geom = QgsGeometry() # Construct a geometry
feat.setGeometry(geom)
feat.setFields(self.layer.pendingFields()) # retrieve the fields from layer and set them to the feature
self.iface.openFeatureForm(self.layer, feat)

The segfault was probably due to the wrong mapping between the layers's fields and the feature's fields.

Like that, the feature form opens as expected and I can save the feature back to my layer.

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.