2

Here is my class

class aClassName():
    def __init__(self):
        #do something...

        iface.setActiveLayer(QgsProject.instance().mapLayersByName('someName')[0])

        #do something
    ...

The class calls a number of methods from iface such as setActiveLayer, .mapCanvas().zoomToSelected() etc in different functions. It runs properly when it is called in the same file.

But when I tried to use the class by importing it into another file:

from theClassFile import aClassName

The error message showed up and said :

NameError: name 'iface' is not defined

even if adding from qgis.utils import iface to theClassFile with reference from here.

I just began to use PyQGIS last month.

Here is my QGIS version: enter image description here

Vincent Bré
  • 4,090
  • 7
  • 23
Pete
  • 355
  • 2
  • 12

1 Answers1

1

I tried in Python console, the following code works.

The content of the file theClassFile.py :

class aClassName():  
    def __init__(self):

        # Replace the name of your layer
        iface.setActiveLayer(QgsProject.instance().mapLayersByName('alaska')[0])
        print('OK !')

The contents of the main script :

from qgis.utils import iface
from qgis.core import *

import sys 
# Path of theClassFile.py directory
sys.path.append(r'C:/Users/v.bre/Desktop/test/iface_double_scripts/')

from theClassFile import aClassName

aClassName()

I have two layers in my QGIS project. With this code, I change the active layer and I print a message. There are many bugs, if you modify theClassFile.py, QGIS will not take the changes into account. To solve this problem, sometimes think about restarting your QGIS.

Try this code and get back to me.

Vincent Bré
  • 4,090
  • 7
  • 23
  • I tried the code by adding data=None at __init__ and . before the imported file. It shows ModuleNotFoundError: No module named '__console__' pointing to the first line of the main script. – Pete Dec 30 '19 at 09:22
  • Maybe I made a mistake. Are you working in the Python console editor or are you in a plugin? – Vincent Bré Dec 30 '19 at 09:25
  • I'm working in Python console in QGIS – Pete Dec 30 '19 at 09:27
  • Sorry, my code is an exemple of plugin code. – Vincent Bré Dec 30 '19 at 09:46
  • I edited my code. – Vincent Bré Dec 30 '19 at 10:23
  • I added the new path as suggested, the error changed to NameError: name 'processing' is not defined. I tried to follow the solution here, but it didn't work. – Pete Dec 31 '19 at 02:29
  • Can you try to just copy my code, you shouldn't get an error in the QGIS Python console because all QGIS modules are imported by default. – Vincent Bré Dec 31 '19 at 09:16
  • I pasted provided code and changed the layer name and file path to my own, but NameError: name 'iface' is not defined still appeared. p.s. aClassName works fine when called within the theClassFile.py – Pete Jan 02 '20 at 02:56