[EN]Developing a QGIS Plugin Compatible with QGIS 3 and QGIS 4: Preparing for the Move to Qt6


The transition from QGIS 3 to QGIS 4 raises an important question for plugin developers: should you plan to maintain two versions of your extension, or can you write code today that will work in both environments?

This question is particularly relevant for professional development. Consider a plugin designed to interact with a PostgreSQL/PostGIS database in a company currently using QGIS 3.40 and planning to migrate to QGIS 4.

The good news is that a large part of the code can be retained. However, compatibility is not achieved simply by replacing a few imports. Certain good practices need to be adopted from the beginning of development.

Let’s see how.



1. Why does QGIS 4 change the development environment?

QGIS plugins are developed in Python. They use two sets of features:

  • PyQGIS, which provides access to QGIS-specific functionality: projects, layers, features, geometries, processing tools, etc.
  • PyQt, which is used to build graphical interfaces: windows, buttons, input fields, menus and other components.

The transition from QGIS 3 to QGIS 4 mainly involves a change in the version of Qt and its Python bindings.

EnvironmentGUI libraryPython bindings
QGIS 3.x (standard)Qt 5PyQt5
QGIS 4.xQt 6PyQt6

This change introduces differences in certain classes, imports, enumerations and available methods.

However, this does not mean that existing plugins need to be completely rewritten.

The fundamental principles remain the same: Python classes, object-oriented programming, signals and slots, widgets, layouts, layer management and data access through PyQGIS.

The goal is therefore to limit direct dependencies on a particular version of Qt.


2. The essential rule: use qgis.PyQt

When developing a QGIS plugin, it is preferable not to import PyQt5 or PyQt6 modules directly.

Avoid:

from PyQt5.QtWidgets import QDialog, QPushButton
from PyQt5.QtCore import Qt

Also avoid:

from PyQt6.QtWidgets import QDialog, QPushButton
from PyQt6.QtCore import Qt

Instead, use:

from qgis.PyQt.QtWidgets import QDialog, QPushButton
from qgis.PyQt.QtCore import Qt

The qgis.PyQt module is a compatibility layer provided by QGIS. It allows you to use Qt classes without directly depending on the name of the installed PyQt library.

This is an important rule for a plugin intended to run under both QGIS 3 and QGIS 4.

However, be aware that this compatibility layer does not automatically make all APIs identical. Differences between Qt5 and Qt6 still need to be taken into account.


3. The main differences between PyQt5 and PyQt6

3.1. Qt enumerations

This is one of the most visible differences.

With PyQt6, enumerations are more structured: constants are grouped into specific classes.

PyQt5 – old syntaxPyQt6 – new syntax
Qt.AlignLeftQt.AlignmentFlag.AlignLeft
Qt.AlignCenterQt.AlignmentFlag.AlignCenter
Qt.HorizontalQt.Orientation.Horizontal
Qt.VerticalQt.Orientation.Vertical
Qt.UserRoleQt.ItemDataRole.UserRole
Qt.WaitCursorQt.CursorShape.WaitCursor
Qt.blueQt.GlobalColor.blue

For development intended to work with both generations of QGIS, it is preferable to adopt the new syntax, provided that the selected minimum QGIS 3 version supports it.

For example:

from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QLabel

label = QLabel("Hello QGIS")

label.setAlignment(
    Qt.AlignmentFlag.AlignCenter
)

You should therefore check that the enumerations you use are compatible with the minimum QGIS 3 version you intend to support.


3.2. Enumerations in the QGIS API

The same principle applies to the QGIS API. Some constants have been grouped into enumeration classes.

Old syntaxNew syntax
QgsWkbTypes.PolygonGeometryQgsWkbTypes.GeometryType.PolygonGeometry
QgsMapLayer.VectorLayerQgsMapLayer.LayerType.VectorLayer
Qgis.CriticalQgis.MessageLevel.Critical

Example:

from qgis.core import QgsWkbTypes

if layer.geometryType() == QgsWkbTypes.GeometryType.PolygonGeometry:
    print("Polygon layer")

These explicit forms should be preferred when developing for both generations of QGIS, subject to the selected minimum QGIS 3 version.


3.3. Starting the Qt event loop

With PyQt5, you will often encounter:

app.exec_()

With PyQt6, the method is:

app.exec()

For compatible code, use exec() when the targeted minimum QGIS 3 version allows it.

However, remember that a QGIS plugin runs within an application that already has its own event loop. You should therefore not create a new QApplication instance or call app.exec() from a plugin.


3.4. Buttons and dialog boxes

Connections between signals and slots generally remain unchanged.

For example:

self.button.clicked.connect(self.validate)

However, constants used with dialog boxes may change.

Old syntax:

QMessageBox.Ok
QMessageBox.Cancel

New syntax:

QMessageBox.StandardButton.Ok
QMessageBox.StandardButton.Cancel

For new developments, prefer:

from qgis.PyQt.QtWidgets import QMessageBox

response = QMessageBox.question(
    self,
    "Confirmation",
    "Do you want to continue?",
    QMessageBox.StandardButton.Yes |
    QMessageBox.StandardButton.No
)

Here again, you need to check that these forms are available in the selected minimum QGIS 3 version.


3.5. Qt classes and their modules

Some classes have moved between modules from Qt5 to Qt6.

One important example is QAction:

In Qt5, it is generally imported from QtWidgets.

In Qt6, it belongs to QtGui.

You therefore need to check imports in the actual QGIS environment you are targeting. Using qgis.PyQt is recommended, but it does not remove the need to check classes that have moved and their import modules.


4. Separating the interface, business logic and data access

This is probably the most important piece of advice for a professional plugin.

If you are developing an extension intended to communicate with a PostgreSQL/PostGIS database, it is preferable not to mix SQL statements, business operations and graphical interface construction instructions.

You can distinguish three main parts.


4.1. The graphical interface

This includes the elements with which the user interacts:

  • Windows and dialog boxes
  • Buttons and menus
  • Input fields
  • Selection lists
  • Display of results and messages

This part depends mainly on Qt and PyQt. It is therefore the part most likely to require adjustments when moving to QGIS 4.


4.2. Business logic

This contains the operations specific to how the plugin works:

  • Parameter checks
  • Business rules
  • Calculations
  • Data transformations
  • Operation sequences
  • Result validation

As far as possible, this part should be independent of the graphical interface.

A business operation should not need to know how a user entered a value in a form. It should receive that value as a parameter and return a result.


4.3. Data access

This part groups together operations that communicate with PostgreSQL/PostGIS:

  • Opening and closing connections
  • Executing SQL queries
  • Retrieving results
  • Managing transactions
  • Handling connection errors

Depending on your requirements, you can use QGIS data providers, PyQGIS connection classes or a Python library such as psycopg.

The choice depends in particular on the type of operations being performed and how you want to manage transactions.


4.4. Example of a plugin structure

One possible structure would be:

my_plugin/
│
├── __init__.py
├── metadata.txt
├── my_plugin.py
│
├── interface/
│   ├── __init__.py
│   └── dialog.py
│
├── business/
│   ├── __init__.py
│   └── processing.py
│
├── data/
│   ├── __init__.py
│   └── postgres.py
│
├── resources.py
├── resources.qrc
└── icon.png

In this structure:

  • dialog.py manages interactions with the user;
  • processing.py contains business operations;
  • postgres.py handles communication with the database;
  • my_plugin.py coordinates the different parts.

This separation makes it possible to limit the changes required when Qt or PyQt evolves.

For example, if you need to modify the layout of a dialog box for QGIS 4, the SQL queries and business rules should normally not need to be changed.

This structure is also easier to test and maintain.


5. Graphical resources

Plugins can use external resources: icons, images, stylesheets, etc.

There are two possible approaches.

Direct access to files

icon_path = os.path.join(
    plugin_dir,
    "icons",
    "icon.png"
)

icon = QIcon(icon_path)

This method is simple and does not depend on the Qt resource system.

Using the Qt resource system

.qrc files are compiled into Python modules, often named resources.py.

The resource compilation tools differ depending on the PyQt generation. You should therefore check the compilation workflow if your plugin uses this system.

For a simple plugin, direct access to files may be easier to maintain.


6. What does not change

Most of the concepts used in QGIS plugin development remain valid.

ElementSituation
Python classesUnchanged
Object-oriented programmingUnchanged
Action managementSame principle
Signals and slotsSame principle
QDialog and QMainWindowSame principle
QFrame and layoutsSame principle
QVBoxLayout and QHBoxLayoutSame principle
QPushButton, QLabel, QLineEditSame principle
QgsProjectSame principle
QgsVectorLayerSame principle
QgsFeature and QgsGeometrySame principle
Attribute accessSame principle
Layer managementSame principle

PyQGIS methods may nevertheless evolve between QGIS versions. It is important not to confuse changes to Qt/PyQt with changes specific to the QGIS API.


7. Python version and dependencies

The Python version also depends on the installed QGIS version.

You should not assume that all QGIS 3.x versions use the same Python version.

When developing a plugin, it is recommended to work with the Python interpreter supplied with the targeted QGIS installation.

In particular, avoid testing a plugin in an independent Python environment that does not contain the same libraries as QGIS.

This is especially important for plugins that use external libraries.

If your plugin depends on psycopg, for example, you need to check that the library is available and compatible with the Python versions used by the targeted QGIS installations.

Moving to QGIS 4 may therefore require checking not only PyQt code, but also Python dependencies and any compiled extensions they may contain.


8. Developing a plugin compatible with QGIS 3 and QGIS 4

It is possible to maintain a single source code base for both generations of QGIS.

A few rules make this compatibility easier:

  • Use qgis.PyQt for Qt imports.
  • Prefer the new enumeration syntax.
  • Avoid obsolete or removed Qt methods.
  • Check imports for classes that have moved.
  • Check Qt resources if the plugin uses .qrc files.
  • Check Python dependencies.
  • Test the plugin in the QGIS versions actually targeted.

8.1. Adjusting plugin metadata

The metadata.txt file contains the plugin’s compatibility information.

For a plugin intended to work from QGIS 3.40 onwards and with subsequent QGIS 4 versions, you could specify:

[general]
name=My plugin
version=1.0
qgisMinimumVersion=3.40
qgisMaximumVersion=4.99

The qgisMaximumVersion value should be adapted to the plugin’s compatibility strategy.

Obviously, declaring a maximum version is not enough to make a plugin compatible: the code must actually have been tested.

Note: the former supportsQt6=True metadata entry, used during a transition period, is no longer recognised by QGIS. The qgisMinimumVersion and qgisMaximumVersion fields now determine the declared version range.


9. Tools for preparing the migration

Several resources can help developers.


9.1. The QGIS migration guide

The official QGIS wiki describes the differences between Qt5 and Qt6 and explains how to adapt a plugin so that it works in both environments.

It covers, in particular, the new enumeration syntax and API changes.

Guide: https://github.com/qgis/QGIS/wiki/Plugin-migration-to-be-compatible-with-Qt5-and-Qt6


9.2. The PyQt5-to-PyQt6 migration script

QGIS provides a script that can identify and transform certain PyQt5 expressions into PyQt6 equivalents.

It can, for example, work on imports and enumerations.

This script is a migration aid, but running it should not be considered a guarantee of compatibility. The proposed changes must be reviewed, and the plugin must be tested.


9.3. PyQGIS 4 Checker

The official pyqgis4-checker project provides tools to check and prepare plugins for migration to QGIS 4.

GitHub repository: https://github.com/qgis/pyqgis4-checker

It can perform checks for detectable incompatibilities and provides migration tools. The repository evolves alongside QGIS, so it is best to consult its documentation for the current usage instructions.


9.4. The official plugin repository checks

The official QGIS plugin repository also includes an automatic Qt6 compatibility check when a new plugin version is submitted.

The results are available on the plugin version page. They can help identify certain problems in the code, but they do not replace testing in a QGIS 4 environment.

Documentation: https://plugins.qgis.org/docs/migrate-qgis4


9.5. Riverbank Computing documentation

Riverbank Computing’s documentation describes the differences between PyQt5 and PyQt6.

It is useful for understanding syntax changes and developments in Qt classes.

https://www.riverbankcomputing.com/static/Docs/PyQt6/pyqt5_differences.html

10. Recommended workflow

For a developer starting a plugin today under QGIS 3.40 and wishing to prepare for its use under QGIS 4, I recommend the following approach:

  1. Keep the QGIS 3 production environment. It remains the reference for initial development.
  2. Always use qgis.PyQt. Avoid direct imports from PyQt5 or PyQt6.
  3. Adopt the new enumeration syntax. Check that it is available in the minimum QGIS 3 version.
  4. Separate the plugin’s responsibilities. The interface, business logic and data access should be organised into separate modules.
  5. Avoid obsolete Qt methods. It is better to address these issues during development rather than waiting for migration.
  6. Test the plugin regularly under QGIS 3. Make sure that compatibility choices do not compromise the environment currently in use.
  7. Prepare a QGIS 4 test environment. As soon as possible, install a separate version to check that the plugin works.
  8. Use migration checking tools. They help identify incompatibilities before manual testing.

For a professional plugin, it is also worth automating some of the tests. A Git repository and continuous integration can be used to check the same code in several QGIS environments.


Conclusion

Moving from QGIS 3 to QGIS 4 does not mean that you have to start from scratch when developing plugins.

By using qgis.PyQt, preferring the new enumeration syntax and avoiding obsolete methods, you can considerably reduce the changes required.

However, the best way to prepare for this transition is to adopt a good software architecture. By separating the graphical interface, business logic and data access, you isolate the parts that are likely to change and make code reuse easier.

For a PostgreSQL/PostGIS plugin, SQL queries and business operations can therefore largely be retained, while Qt-related changes are concentrated in the interface layer.

The rule remains the same: a plugin is only compatible with QGIS 4 once it has actually been tested in that environment.


🔗 Links to the other articles in the series

🔹 Understanding the context

To put this article into context, you can read:


🔹 Getting started


🔹 Before Modifying Data

The following articles cover the essential concepts to understand before modifying data:


🔹 Making your plugin more reliable


🔹 Organize, document, and distribute your plugin


🔹 Useful Related Articles

These additional articles help avoid common mistakes:


Si cet article vous a intéressé et que vous pensez qu'il pourrait bénéficier à d'autres personnes, n'hésitez pas à le partager sur vos réseaux sociaux en utilisant les boutons ci-dessous. Votre partage est apprécié !
Atilio Francois
Atilio Francois
Articles: 1061

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you human? Please solve:Captcha