8

I have the following script that sets the a feature id automatically after a new feature is digitized.

I want the following function to be executed automatically when project is opened (and layers are loaded) so that users don't need to do anything.

import os

# Set layer by Name

layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "Pozos":
        layer = lyr
        break

# Define function to select added feature and add attribute to field "id"
def update(featureAdded):
    idx = layer.fieldNameIndex('id')
    max = layer.maximumValue(idx) +1
    layer.changeAttributeValue(featureAdded, idx, max)

# Connect "featureAdded" event to "select" function
layer.featureAdded.connect(update)

I tried adding the function inside the project's Macro section inside openProject() function:

enter image description here

But when the project is opened I get:

enter image description here

It looks like QgsMapLayerRegistry is not loaded when the function is triggered?

2
  • 2
    @Joseph That did the trick! Can you post the answer so that I can mark it as the valid one?
    – Egidi
    Commented May 24, 2016 at 12:35
  • Awesome, glad you got it working =)
    – Joseph
    Commented May 24, 2016 at 12:54

2 Answers 2

11

To fix the error:

NameError: global name 'QgsMapLayerRegistry' is not defined

Just add the following at the top of your script:

from qgis.core import QgsMapLayerRegistry

Tip:

What I do normally when I receive similar errors is to type the class into the Python Console. It will then provide you with a list of classes and libraries in which they belong to:

Typing in class

Or you can just type it in the console and press 'Enter':

Class

In both cases, we can see that we need to call qgis.core in order to import the QgsMapLayerRegistry class.

9

Within QGIS 3.0 and above updates took place within the API, QgsMapLayerRegistry has been removed and its functionality has been moved to QgsProject.

As a beginner, I found it confusing because they didn't make an update for the Developer Cookbook pdf version. This has also been answered in Is QgsMapLayerRegistry removed in QGIS3?

Your Answer

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

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