I am in the process of migrating a QGIS python plugin from QGIS 2
to QGIS 3
, and browsing various resources.
It's not clear if it's possible to have the plugin compatible with both versions or if it's necessary two handle to plugin versions.
The problem I hit so far is how to manage PyQt import (PyQt4/PyQt5) ?
Best Answer
Documentation
Here you can find what is new and what is break under the PyQGIS API.
To get details about how to port Python2 to Python3 go there
You can find some detail about testing from QGIS2 to QGIS3 on this question :Writing automated tests for QGIS plugins?
And you will find an interesting OpenGis.ch's paper here about the migrations tools.
What will change into my code
In fact, you need to change code of plugin that are not prepared to pass throught a new version.
You get qgis.utils.QGis.QGIS_VERSION_INT function which is made to check the QGIS version. This is usefull when a function is deprecabled . For exemple
setSelectedFeatures
since 2.16.By exemple with the use of
if
statement :It's the same about
PyQt
object you import under your module. If you need compatibility, the price is to wrote more code line (the code with QGIS2 function and the code with QGIS3 functions AND also the code for checking the version and the capabilities to import new libraries ).About PyQt libraries
source : (http://zetcode.com/gui/pyqt5/introduction/)
Here is some exemples of changes into your from/import statement:
Remember with PyQt4 you had to look on the API's doc:
for exemple
PyQT4 QtCore module
PyQT4 QtGui module
And with PyQt5 you have now to look on those API's doc :
PyQt5 QtCore module
PyQt5 QtGui module
so that become :
Note that :
And PyQt5 supports only the new-style signal and slots handlig! have a look to this page to understand how to use
pyqtSignal
,connect
ande
event object instead of useSIGNAL
.Make it compatible
So with compatibility between PyQt4/PyQt5 (and QGIS2 / QGIS3 as well) you need to try/except the import before use the pyQt5 librarie.
And don't forget that you need to change also some specific function under your code by adding try/except or if statement.