Plugin Boilerplate & Structure
A well-defined plugin boilerplate and directory structure is the foundation of any maintainable PyQGIS extension. QGIS expects a predictable file hierarchy, standardized metadata, and explicit lifecycle hooks. When these elements are correctly implemented, the plugin manager can load, initialize, and unload your code without conflicts. This guide sits within the broader QGIS Plugin Development track: it establishes the skeleton every later stage builds on — the visual interface you design in Qt Designer for QGIS interfaces, the algorithms you expose through processing provider plugins, the automated checks in testing and CI for plugins, and the release you eventually send to the QGIS plugin repository.
This page targets QGIS 3.x on Python 3 and pins its examples to the 3.34 LTR line, noting API differences where they matter. Read it top to bottom to build a correct skeleton by hand, then branch into the focused recipes linked throughout — scaffolding with Plugin Builder 3 if you would rather generate the tree, and adding a toolbar button once the class is in place.
Prerequisites
Before generating or modifying a plugin skeleton, ensure your environment meets the following baseline requirements:
- QGIS 3.x installed — pin against the current LTR (3.34) so your
qgisMinimumVersionand API assumptions match the release most users run. - Python 3.9+ environment (bundled with modern QGIS releases).
- A code editor with Python syntax highlighting and linting (VS Code, PyCharm, or similar).
- Basic familiarity with object-oriented Python and Qt signal/slot architecture — the same signal wiring covered in Qt Designer for QGIS interfaces.
- Write access to the QGIS profile directory.
The QGIS profile directory typically resides at:
- Windows:
%APPDATA%\QGIS\QGIS3\profiles\default\python\plugins\ - macOS/Linux:
~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/
Standard Directory Architecture
A compliant plugin directory must contain specific files that QGIS scans during startup. The following tree represents the minimal viable structure:
my_plugin/
├── __init__.py
├── metadata.txt
├── main_plugin.py
├── resources.qrc
├── ui/
│ └── main_dialog.ui
├── i18n/
│ └── my_plugin_en.ts
└── icons/
└── icon.png
File Responsibilities:
__init__.py: Entry point that exposes theclassFactoryfunction to QGIS.metadata.txt: Plain-text configuration file containing plugin name, version, author, and QGIS compatibility flags.main_plugin.py: Core logic handling GUI initialization, toolbar/menu integration, and cleanup routines.resources.qrc: Qt resource compiler file bundling icons and UI assets.ui/: Contains.uiXML files generated by Qt Designer.i18n/: Translation files for internationalization.icons/: Raster or SVG assets for toolbar buttons and plugin manager listings.
This layout is exactly what a scaffolding tool emits: if you run Plugin Builder 3, it generates the same tree plus a Makefile and a test/ package. Building it by hand once, however, makes every later file feel obvious rather than magic.
Step-by-Step Implementation Workflow
- Create the Root Directory: Name it using lowercase letters and underscores (e.g.,
spatial_analyzer). Avoid spaces or special characters — the folder name becomes the Python package name. - Generate
metadata.txt: Populate required keys. QGIS will reject plugins missingname,version,qgisMinimumVersion, ordescription. - Implement
__init__.py: Define a singleclassFactoryfunction that returns your main plugin class instance. - Build
main_plugin.py: Define a standard Python class that acceptsiface. ImplementinitGui(),unload(), andrun(). - Compile Resources: Use
pyrcc5to convertresources.qrcinto a Python-importable module (resources_rc.py). - Load & Test: Enable the plugin in QGIS via
Plugins → Manage and Install Plugins → Installed → Enable. Monitor the Python Console for traceback output.
Core File Breakdown & Tested Code Patterns
1. Entry Point (__init__.py)
This file must be lightweight. QGIS calls classFactory(iface) during plugin discovery.
def classFactory(iface):
"""
Factory function required by QGIS.
:param iface: QgsInterface instance providing access to the QGIS API
:return: Main plugin class instance
"""
from .main_plugin import SpatialAnalyzerPlugin
return SpatialAnalyzerPlugin(iface)
2. Metadata Configuration (metadata.txt)
Use strict key-value formatting. Do not include blank lines between keys.
[general]
name=Spatial Analyzer
qgisMinimumVersion=3.34
description=Provides advanced spatial analysis tools for vector layers.
version=1.0.0
author=Your Name
email=your.email@example.com
about=This plugin extends QGIS with custom geoprocessing workflows.
tracker=https://github.com/yourname/spatial-analyzer/issues
repository=https://github.com/yourname/spatial-analyzer
icon=icons/icon.png
experimental=False
deprecated=False
Pinning qgisMinimumVersion to 3.34 targets the current LTR. If you rely on an API added in a later feature release, raise this value — QGIS hides the plugin from users on older builds rather than letting it fail at runtime. The full set of keys the official repository validates is covered in publishing to the QGIS plugin repository.
3. Main Plugin Class (main_plugin.py)
The lifecycle here is the heart of the boilerplate: QGIS instantiates the class, calls initGui() to register interface elements, invokes run() when the user triggers your action, and calls unload() when the plugin is disabled. Every element you add in initGui() must be removed in unload() — the two methods are mirror images, and treating them that way is what keeps the interface clean.
The following pattern demonstrates safe GUI registration, robust path resolution, and clean teardown.
import os
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import Qgis
class SpatialAnalyzerPlugin:
def __init__(self, iface):
self.iface = iface
self.plugin_dir = os.path.dirname(__file__)
self.actions = []
self.menu = self.tr("&Spatial Analyzer")
self.toolbar = self.iface.addToolBar("SpatialAnalyzer")
self.toolbar.setObjectName("SpatialAnalyzer")
# Initialize translation with safe fallback
locale = QSettings().value("locale/userLocale", "en_US")[0:2]
locale_path = os.path.join(self.plugin_dir, "i18n", f"spatial_analyzer_{locale}.qm")
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
def tr(self, message):
return QCoreApplication.translate("SpatialAnalyzerPlugin", message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None,
):
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip:
action.setStatusTip(status_tip)
if whats_this:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(self.menu, action)
self.actions.append(action)
return action
def initGui(self):
"""Initialize GUI elements when plugin loads."""
icon_path = os.path.join(self.plugin_dir, "icons", "icon.png")
self.add_action(
icon_path,
text=self.tr("Run Analysis"),
callback=self.run,
parent=self.iface.mainWindow(),
)
def unload(self):
"""Remove GUI elements and clean up resources."""
for action in self.actions:
self.iface.removePluginMenu(self.menu, action)
self.iface.removeToolBarIcon(action)
# Safely remove the custom toolbar
self.iface.mainWindow().removeToolBar(self.toolbar)
self.actions.clear()
def run(self):
"""Execute plugin logic."""
layer = self.iface.activeLayer()
if not layer:
self.iface.messageBar().pushMessage(
"Warning",
"Please select a vector layer first.",
level=Qgis.Warning,
duration=3,
)
return
# Core processing logic goes here
self.iface.messageBar().pushMessage(
"Success",
f"Analysis initialized for {layer.name()}",
level=Qgis.Success,
duration=3,
)
The add_action() helper is deliberately generic so that every button, menu entry, and shortcut passes through one registration path that also appends to self.actions. That single list is what makes unload() reliable. For the full breakdown of registering a single QAction — including mirroring it into a plugin menu and wiring the triggered signal — follow Add a Toolbar Button to a QGIS Plugin.
4. Wiring in a Dialog
Most plugins do more than fire a message bar notification: they open a dialog built in Qt Designer. Keep the layout in a .ui file and load it at runtime rather than compiling it, so a pyuic5 version mismatch never breaks an end-user install. Instantiate the dialog inside run():
def run(self):
from .ui.main_dialog import SpatialAnalyzerDialog
dlg = SpatialAnalyzerDialog(self.iface.mainWindow())
if dlg.exec_():
# read validated inputs from dlg, then dispatch the work
...
The dialog class itself — uic.loadUiType(), setupUi(), promoted QGIS widgets, and signal connections — is covered end to end in Qt Designer for QGIS interfaces. Keep the heavy geoprocessing off the constructor and out of the main thread: long-running work belongs in a QgsTask or, better, in a reusable algorithm registered through a processing provider plugin, which gives you batch execution and Model Builder support for free.
5. Extending the Boilerplate
Once the base structure is stable, you can branch into specialized implementations. If your plugin requires field calculator integration, adapt the initialization sequence to support custom expression functions, which requires explicit registration with QgsExpression.registerFunction() during initGui() and deregistration in unload() — the same symmetric setup/teardown discipline the rest of the class already follows. As soon as the module has real logic, add coverage for it; the headless test harness in testing and CI for plugins mocks iface so initGui()/unload() can be exercised without a running desktop.
Common Errors & Resolution Strategies
1. Plugin Not Appearing in Manager
Symptom: The directory exists but QGIS ignores it.
Cause: Missing metadata.txt, malformed keys, or qgisMinimumVersion higher than the installed QGIS version.
Fix: Verify metadata.txt syntax. Ensure qgisMinimumVersion matches or is lower than your QGIS build. Check View > Log Messages > Python Errors for PluginManager warnings.
2. ModuleNotFoundError or Import Failures
Symptom: ImportError: cannot import name 'main_plugin'Cause: Relative import issues or missing __init__.py in subdirectories.
Fix: Always use relative imports (from .main_plugin import ...). Ensure every Python-containing directory has an empty __init__.py. Avoid absolute paths; QGIS modifies sys.path dynamically during plugin loading.
3. UI Dialog Fails to Load
Symptom: QFile::open: No such file or directory when loading .ui files.
Cause: Incorrect working directory assumption. QgsApplication does not guarantee the current working directory matches the plugin folder.
Fix: Resolve paths using os.path.dirname(__file__) before passing them to uic.loadUiType(). Example:
ui_path = os.path.join(os.path.dirname(__file__), "ui", "main_dialog.ui")
4. Toolbar/Menu Items Persist After Unload
Symptom: Buttons remain visible after disabling the plugin.
Cause: unload() does not explicitly remove registered actions.
Fix: Store all QAction instances in a list during initGui() and iterate through them in unload(), calling both removePluginMenu() and removeToolBarIcon(). Never rely on QGIS to garbage-collect UI references automatically.
5. Resource Compilation Errors
Symptom: pyrcc5 fails or icons appear as broken placeholders.
Cause: Invalid paths in resources.qrc or missing qrc file in the plugin directory.
Fix: Run compilation from the plugin root: pyrcc5 resources.qrc -o resources_rc.py. Verify all <file> tags in the .qrc use paths relative to the .qrc location.
Workflow Validation Checklist
Before considering the boilerplate complete, verify the following:
-
metadata.txtcontains all required fields and valid version strings -
__init__.pyexposes exactly oneclassFactoryfunction -
initGui()registers actions andunload()removes them symmetrically - All file paths resolve using
__file__rather thanos.getcwd() - Plugin loads without traceback in a fresh QGIS profile
- Toolbar and menu items disappear completely after disabling
- Translation files load gracefully when missing
The load sequence, and what fails where
A plugin passes through four stages before it is usable, and each stage has its own failure symptom. Recognising which stage failed narrows the cause immediately.
The fourth is the one that looks most mysterious: the plugin is listed, ticked and apparently loaded, yet nothing appears in the interface. That is nearly always initGui() raising partway through — commonly on an icon path that does not resolve — leaving the actions created before the exception installed and everything after it missing.
Key Takeaways
- The directory is a contract: QGIS reads
metadata.txtfirst, imports__init__.py, and expectsclassFactory(iface)to return your main class. Get those three right and the plugin manager can see your code. - Keep
__init__.pytrivial and defer the real import intoclassFactoryso a heavy module never loads at scan time and one broken plugin cannot take down the manager. initGui()andunload()are mirror images. Route every interface element through oneadd_action()-style helper that also records it, so teardown is a simple loop.- Resolve every path from
os.path.dirname(__file__), never the current working directory — QGIS does not guarantee where it runs from. - Ship
.uifiles raw and load them at runtime; onlyresources.qrcneeds thepyrcc5step. PinqgisMinimumVersionto the LTR you test against.
With a clean skeleton in place, the next steps are the interface (Qt Designer), reusable logic (processing providers), automated checks (testing and CI), and release (publishing).
Frequently Asked Questions
Why must __init__.py only contain the classFactory function and a deferred import?
QGIS imports __init__.py during plugin discovery, before the user enables the plugin. Keeping it lightweight and importing your main module inside classFactory (from .main_plugin import ...) prevents heavy modules from loading at scan time and stops an import error in one plugin from breaking the entire plugin manager.
What happens if metadata.txt is missing or has a malformed key?
QGIS silently skips the directory and the plugin never appears in the plugin manager. Required keys are name, version, qgisMinimumVersion, and description; missing any one, or adding blank lines between keys, causes the parser to reject the file. Check View > Log Messages > Python Errors for PluginManager warnings when a folder is ignored.
Do I need to compile .ui files into the plugin structure?
No. The recommended pattern loads the .ui file at runtime with uic.loadUiType(), so you ship the raw .ui inside the ui/ folder rather than a compiled module. You only run pyrcc5 to turn resources.qrc into resources_rc.py, since Qt's resource system cannot read .qrc directly at runtime.
Where should the plugin folder live during development?
Place it in the active QGIS profile's python/plugins/ directory — %APPDATA%\QGIS\QGIS3\profiles\default\python\plugins\ on Windows or ~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/ on macOS/Linux. The folder name becomes the import package name, so use lowercase letters and underscores with no spaces.
Why do toolbar buttons sometimes remain after I disable a plugin?
QGIS does not automatically garbage-collect QAction references you added in initGui(). Store every action in a list and, in unload(), call both removePluginMenu() and removeToolBarIcon() for each, then remove any custom toolbar you created. Symmetric setup and teardown is the only reliable way to keep the interface clean.
Does this boilerplate change between QGIS 3.x versions?
The core contract — metadata.txt, classFactory, initGui/unload — has been stable across the entire QGIS 3 series. What shifts is the API surface you call inside run(): enums and helper classes occasionally move between feature releases. Pin qgisMinimumVersion to the LTR you develop against (3.34 here) and consult the QGIS API changelog before adopting methods introduced in a newer build.
Why does my plugin not appear in the Plugin Manager?
QGIS discovers plugins by looking for a metadata.txt inside a folder directly under the profile's python/plugins directory. A missing metadata file, or a folder nested one level too deep, means the plugin is never seen at all — there is no error because nothing was found to report on.
What must classFactory return?
An instance of your plugin class, constructed with the iface argument it receives. Returning None, or raising anything, produces a traceback when the user ticks the plugin and leaves it disabled.
Is unload() really necessary? Yes, for anything you intend to develop iteratively. Without it a reload leaves duplicate toolbar buttons, doubled signal handlers and orphaned map tools, and the resulting behaviour is far more confusing than the original bug you were trying to fix.
Where does QGIS look for plugins?
Inside the active user profile, under python/plugins. The profile directory is shown by Settings, User Profiles, Open Active Profile Folder, which is more reliable than guessing the path for your platform.
Does the folder name matter? Yes — it becomes the Python package name, so it must be a valid identifier and must match the name used when the plugin is packaged for the repository.
Can two plugins share a folder name? No. The folder name is the Python package name and the repository identifier, so a collision means one of the two will not load. Prefix an organisation-specific name to make an accidental clash unlikely.
Related Guides
- Up: QGIS Plugin Development — the parent guide covering the full plugin journey.
- Create a QGIS Plugin with Plugin Builder 3 — scaffold this exact structure automatically.
- Add a Toolbar Button to a QGIS Plugin — register a
QActionininitGui()and clean it up inunload(). - Qt Designer for QGIS Plugin Interfaces — build the dialog your
run()method opens. - Processing Provider Plugins for QGIS — expose reusable algorithms in the Processing Toolbox.
- Testing & CI for QGIS Plugins — exercise the lifecycle headlessly.
- Publishing to the QGIS Plugin Repository — metadata, versioning, and the approval workflow.