9

I am trying to write a QGIS plugin, which should work on QGIS 2 and QGIS 3. How can I find out which QGIS version the user is using, so the right imports are made?

5 Answers 5

18

In QGis < 3, qgis.core has a QGis object:

>>> from qgis.core import QGis

with various formats of the version string:

>>> QGis.QGIS_VERSION
u'2.18.5'
>>> QGis.QGIS_VERSION_INT
21805

and the release name, fwiw:

>>> QGis.QGIS_RELEASE_NAME
u'Las Palmas'

In versions 3 and above, this module is renamed Qgis for consistency.

There's a bit of a bootstrap problem here, since you can't get the version to figure out if you need to import Qgis or QGis without knowing. So you probably have to wrap it in a try and catch the exception.

try:
    from qgis.core import Qgis
except ImportError:
    from qgis.core import QGis as Qgis
0
7

You can call simply try this inside your plugin

from qgis.core import *
print QGis.QGIS_VERSION # will print 2.18.13

I dont know if the function is the same in QGIS 3.0 but for 2.18 this worked. The link to the reference can be found here in the pyqgis documentation

3

Just a tiny extension to the @Spacedman's answer.

Since QGIS 3.12, there are several methods (version(), versionInt(), and releaseName()) provided via the Qgis class.

from qgis.core import Qgis

print(Qgis.version()) #3.28.10-Firenze
print(Qgis.versionInt()) #32810
print(Qgis.releaseName()) #Firenze

The same what this code does:

from qgis.core import Qgis

print(Qgis.QGIS_VERSION) #3.28.10-Firenze
print(Qgis.QGIS_VERSION_INT) #32810
print(Qgis.QGIS_RELEASE_NAME) #Firenze
1

We can also use variables:

from qgis.core import QgsExpressionContextUtils 

print(QgsExpressionContextUtils.globalScope().variable('qgis_version'))
# '3.34.10-Prizren'

Or without the slightly annoying town name:

from qgis.core import QgsExpressionContextUtils

print(QgsExpressionContextUtils.globalScope().variable('qgis_version').split('-')[0])
# '3.34.10'
0

This code worked well on my system:

Input:

from qgis.core import Qgis
print (Qgis.QGIS_VERSION)

Output:

3.30.0-'s-Hertogenbosch
2
  • Dear @CarlosOliveira, it is a pleasure to see new members on the GIS SE. It is a great beginning! :) May I kindly ask you, how does your answer differ from @Spacedman's answer?
    – Taras
    Commented Dec 20, 2023 at 17:25
  • And this code should be used since QGIS 3.12. It has been replaced with a new API, describe with the answer from @Taras. Your code example will be removed with QGIS 4.0
    – etrimaille
    Commented Sep 16 at 10:27

Your Answer

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

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