I have this code provided by @Joseph but lose it whenever I leave the QGIS and I have to load it on the Python Console whenever reopen QGIS.

What to do to keep this code in a permanent way?


You can use a project macro to execute python code whenever you open the project.

Navigate to File > Project properties > Macros and insert the code in the openProject() function.

def openProject():
    layer = QgsMapLayerRegistry.instance().mapLayer('the_layer_id')

    def update():
        field = layer.fieldNameIndex('mod')
        e = QgsExpression( " $now " )
        e.prepare( layer.pendingFields() )
        for feat in layer.selectedFeatures():
            feat[field] = e.evaluate( feat )
            layer.updateFeature( feat )


You will have to replace 'the_layer_id' with the layer id in project.

You also need to make sure that Macros are executed Always in the application settings.

  • From where I copy the layer id? May 12 '16 at 11:53
  • 1
    Click the layer and evaluate iface.activeLayer().id() in the python console May 12 '16 at 15:10

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.