Setting a default value in a QGIS field
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)
Since QGIS 2.18, go to the layer properties / field properties and set an expression (@project_filename
in this case) as the default value.
https://www.qgis.org/en/site/forusers/visualchangelog218/index.html#feature-client-side-default-field-values