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?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Egidi
  • 3,738
  • 3
  • 30
  • 55

2 Answers2

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.

Joseph
  • 75,746
  • 7
  • 171
  • 282
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?

Mohab Khaled
  • 136
  • 1
  • 5