13

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.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked May 3, 2016 at 12:21

3 Answers 3

10

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

https://www.qgis.org/en/site/forusers/visualchangelog218/index.html#feature-client-side-default-field-values

answered Nov 9, 2016 at 8:31
0
10

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)

Result

answered May 3, 2016 at 13:26
0
2

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.

enter image description here

answered Feb 24, 2022 at 20:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.