2

With this code you can open a window with a LineEdit, which offers an automatic completion (here index 0).

    my_vector_layer = iface.activeLayer()
    w = qgis.gui.QgsFieldValuesLineEdit()
    w.setLayer(my_vector_layer)
    w.setAttributeIndex(0)
    w.show()

I want to embed this in the object form that appears after adding an object. I'm struggling a little with the PyQGIS documentation. So it's going in this direction:

iface.openFeatureForm(layer, feat, True)
  1. How do I get the above code embedded in openFeatureForm?
  2. Generally I want a link with the attributes of another layer. Without PyQGIS this is possible in the layer properties under attribute form and value relation. But how do I address this and the other control element types of the attribute form in PyQGIS?
4

You can create a specific widget for a specific field to add to the attribute form when it appear. This solution is based on this code by Alexandre Neto and the accepted answer of this post, How to set and configure a value relation edittype in QGIS 2.14? by Matthias Kuhn.

Here is the code :

my_vector_layer = iface.activeLayer() #layer you want to add features to
field = "test" #field you want to relate to another layer
field_idx = my_vector_layer.fields().indexFromName(field) #field index

target_layer = QgsProject.instance().mapLayersByName(layername)[0] #target layer you want to relate to field
key_field = "id" #id field of the target layer
target_field = "test_1" #field of the target layer you want to relate to field

config = {'AllowMulti': False, #don't allow multi value
            'AllowNull': True, #allow NULL value
            'OrderByValue': True, #order by value
            'FilterExpression': '',
            'Key': key_field, #id field of the target layer
            'Value': target_field, #field from the target layer you want to relate
            'Layer': target_layer.id(), #target layer
            'UseCompleter': True} #True if you want the LineEdit tool, False if you want a list of value from the field of the target layer
            

widget_setup = QgsEditorWidgetSetup('ValueRelation',config) #setup a specific widget with Value Relation and the config dict create
my_vector_layer.setEditorWidgetSetup(field_idx, widget_setup) #add the widget to your layer and the field on your layer

This is the result with UseCompleter set to True enter image description here

This is the result with UseCompleter set to False enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.