7

I use iface.activeLayer() intensively. Therefore, when I open QGIS, firstly I use the following script in QGIS Python Editor not to enter iface.activeLayer() everytime.

from qgis.utils import iface
L = iface.activeLayer()

def activeLayerChanged():
    L = iface.activeLayer()

iface.currentLayerChanged.connect(activeLayerChanged)

I thought it would work if I added it to startup.py file. I tried to add the script to startup.py but I got error: name 'L' is not defined.

How can I assing iface.activeLayer() to L (or any single-letter variable) when starting QGIS, so that everytime I enter L, I can get the active layer?

1
  • Doesnt work with any variable when I try it. Like a=1, then a is not found in QGIS
    – BERA
    Apr 16, 2020 at 12:08

2 Answers 2

8

That's a nice use case, but it's not supported nowadays out of the box.

The following is a small hack for you to get such result. Just write this code snippet into your startup.py script:

from qgis.utils import iface
from console import console

if not console._console:
    # We need to initialize the console (QGIS knows how)
    # and respect the opened/closed state from last session
    iface.actionShowPythonDialog().trigger()
    console._console.setVisible(console._console.isUserVisible())

console._console.console.shell.runcode("""
L = None
def clc(layer):
    global L
    L = layer
iface.currentLayerChanged.connect(clc)
""")
console._console.console.shellOut.clearConsole()
0
7

For this, I created a very small plugin with 2 files.

Create a directory in your [...]/QGIS/QGIS3/profiles/default/python/plugins/, for example StartupPlugin.

Create in it the two files below.

Under QGIS, once, active the StartupPlugin in the plugin menu. Then, each times you'll load a project and change your active layer, the Python variable L is created / updated.


  • metadata.txt:
[general]
name=
description=
about=
version=1.0
qgisMinimumVersion=3.0
author=
email=
repository=
  • __init__.py:
from PyQt5.QtWidgets import QMessageBox
from qgis.gui import QgsDockWidget
from console import show_console


def classFactory(iface):
    return StartupPlugin(iface)


class StartupPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.sh = None
        self.iface.projectRead.connect(self.run)
        self.iface.currentLayerChanged.connect(self.activeLayerChanged)

    def initGui(self):
        pass

    def unload(self):
        pass

    def activeLayerChanged(self):
        if self.sh:
            self.sh.runsource("L = iface.activeLayer()")

    def run(self):
        pc = show_console()
        show_console()  # for hide if hidden
        self.sh = pc.console.shell
        self.activeLayerChanged()

Your Answer

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

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