Anyone who has tried it, knows that configuring a Python, PyQGIS, and PyQt environment on Windows for developing QGIS plugins is a real challenge. Often, it feels like a losing battle...
Well, not anymore! After scouring the depths of the internet and exploring tips provided by Julien, here is one method to have (almost) all the auto-completions for PyQGIS, PyQt and more in VS Code.
I will assume that you have installed QGIS in the C:\OSGeo4W directory (the procedure is the same whether QGIS is installed via the OSGeo4W network installer or the MSI package; the paths in this article just need to be adapted to your installation).
Open an OSGeo4W Shell and navigate to the location where you want to create the virtual environment.
For example, a freshly created plugin template using the QGIS Plugin Templater.
Run the following commands:
Creating a virtual environment in the OSGeo4W Shell
In the .venv\pyvenv.cfg file, modify the occurrences of C:\OSGeo4W\bin to C:\OSGeo4W\apps\Python312:
.venv\pyenv.cfg
home=C:\OSGeo4W\apps\Python312include-system-site-packages=trueversion=3.12.6executable=C:\OSGeo4W\apps\Python312\python.execommand=C:\OSGeo4W\apps\Python312\python.exe -m venv --system-site-packages <The full path to your venv>
It is a multi-platform command-line tool (CLI). It is recommended to install it using pipx, which handles most of the tricky setup and is compatible with Windows. It's now the recommended tool in the Python community for managing command-line tools (CLI), so this is a great opportunity to start using it. Once pipx is installed, configured (ensurepath...), and a new PowerShell session is started, the installation runs smoothly:
Installing qgis-venv-creator with pipx
pipxinstallqgis-venv-creator
The qgis-venv-creator tool is now accessible from any PowerShell session with the following command:
Basic command for qgis-venv-creator
create-qgis-venv--venv-name".venv"
The tool needs to identify the QGIS installation to use for generating the development environment. By default, it searches in C:\OSGeo4W and C:\PROGRAMFILES\QGIS X.y.z. However, if you are meticulous and use QGIS in a professional environment, you probably install it in a location recommended by the operating system, such as %PROGRAMFILES%/QGIS/X_y. You can specify a pattern to indicate where it should look:
qgis-venv-creator with a custom QGIS installation path
If you open VS Code in the folder where you just created the virtual environment, VS Code will automatically detect the environment (otherwise, install the VS Code Python extension), and as you type code, VS Code will suggest PyQGIS objects or methods.
To also have all the completions related to PyQt, it seems necessary to install an additional Python library called PyQt5-stubs (although it is no longer maintained, it still works).
In the VS Code terminal, run the following command:
Install PyQT completion in the virtual environment