I would like to add in a layer's field a default value. I mean, every time a new feature is created, that field would be automatically filled with the default value.
In my case the default value would be the @project_filename variable (project's file name).
I can't find this functionality anywhere.
3 Answers 3
Since QGIS 2.18, go to the layer properties / field properties and set an expression (@project_filename
in this case) as the default value.
Expression based default values
You can define a function which adds the project filename as an attribute and connect this function with the event that adds features. You can use the following code, change the name of the field to whatever you choose (I used Name
) and paste it into the Python Console. Now whenever you add a new feature, the field will be populated with the current project name:
import os
# Get project name
project = QgsProject.instance()
project_name = os.path.basename(project.fileName())
# Set active layer
layer = qgis.utils.iface.activeLayer()
# Define function to select added feature and add attribute to field "Name"
def update(featureAdded):
idx = layer.fieldNameIndex('Name')
layer.changeAttributeValue(featureAdded, idx, project_name)
# Connect "featureAdded" event to "select" function
layer.featureAdded.connect(update)
In QGIS 3.x, you can find the "Default Values" section in Layer Properties > Attributes Form ("Manage forms and fields...") section.
Just choose your field, then scroll down to the "Default Values" section on the right hand side.
Explore related questions
See similar questions with these tags.