Assigning a variable for 'iface.activeLayer()' when starting QGIS

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()

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()

Tags:

Qgis

Pyqgis