Python plugin API changes from 1.8 to 2.0¶
- Python plugin API changes from 1.8 to 2.0
- SIP API upgrade
- QVariant removed
- QSettings return type
- Replace QString methods
- Replace QStringList with list
- Remove QVariant calls
- Replace QList methods with python list function
- Replace signals with new style signals and connections
- Vector layer API changes
- QgsFeatureRequest replaces select()
- Getting/setting QgsFeature attributes simplified
- Plugin repository and metadata changes
- Making a plugin compatible with all QGIS versions
- Testing for QGIS version
- Testing for SIP api version (QGIS 2 uses SIP api v2)
This page summarizes the changes needed in migrating QGIS python plugins from the 1.8 API to the 2.0 API. The version 2.0 API has many breaking changes which plugins need to account for.
It is recommended to create a new version of plugins for 2.0, rather than include conditional code to run in both 2.0 and 1.8 in all but the simplest of plugins. Note that both QGIS and the plugin repository distinguish between 1.8 and 2.0 version plugins. QGIS stores 2.0 plugins in a different location (~/.qgis2/python/plugins) to version 1.8, so a user can have both versions installed alongside one another. The repository distinguishes different versions using the plugin metadata.
Please add to this if you find something missing!
SIP API upgrade¶
The SIP API manages the mapping between python and C++/Qt objects. This has been upgraded to version 2. The most significant impact of this is that there is a much tighter mapping between Qt data types and python data types - QVariant and QString are removed. Also the "old style" signal and slot format is no longer available.
The "QVariant" type doesn't exist anymore so any methods returning "QVariant" will be auto converted to Python types. You no longer need to convert the return type using the "toXXXX" methods.
1 toString() 2 toList() 3 toInt() 4 toFloat() 5 toStringList() 6 toByteArray() 7 toPyObject() 8 QVariant(..) 9 QString(...)
Note that the autoconversion to a Python type is based on the type of the QVariant, which may not be the same as the type returned by a toXXX conversion. So new code may need to explicitly set the python type. Note also that some of the toXXX functions return a tuple of (type, valid) to specify whether the conversion is successful. For example:
value,ok = variantValue.toDouble() if not ok: handleError()
# If you are really confident the variant is the type you expect, just use it value = variantValue # Best option to ensure value has the same type as in original code value = float(variantValue) # To handle conversion errors try: value=float(variantValue) except: handleError()
Note: If you do not explicitly set the python type, then you can introduce some subtle errors where the following code assumes a specific type of value. For example value/10 will give a different result depending on whether value is an integer or a float.
QSettings return type¶
The type of QSettings return values is specified in the QSettings.value() call. More info: http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html.
settings.value(“/yourboolsetting”, True).toBool() settings.value(“/yourintsetting”, 10).toInt() settings.value(“/yourintsetting”).toByteArray()
settings.value(“/yourboolsetting”, True, type=bool) settings.value(“/yourintsetting”, 10, type=int) settings.value(“/yourintsetting”, QByteArray(), type=QByteArray)
Replace QString methods¶
"QString" no longer exists in the new QGIS API. Any methods that return a "QString" will be converted into a native Python "unicode". All QString methods need to be replaced with equivalent native string methods.
yourstring.right(4) files.join(",") if yourstring.length() > 4: if yourstring.isEmpty()
yourstring[4:] ",".join(files) if len(yourstring) > 4 if not yourstring
Replace QStringList with list¶
mystrings = QStringList()
mystrings = 
Remove QVariant calls¶
The "QVariant" also doesn't exist as an instantiated type anymore - any methods returning "QVariant" will be auto converted to Python types. However "QVariant" can still be used to access it's enum values e.g. "QVariant.Int" can set be used.
myvalue = QVariant(10) myvalue = QVariant("Hello World")
myvalue = 10 myvalue = "Hello World"
Note that Null QVariant values (ie values for which QVariant.IsNull() returns True) are not mapped to the python None value as you might expect.
Instead they return a QPyNullVariant value. This preserves the type information of the null object.
Replace QList methods with python list function¶
if files.isEmpty() files.count()
if not files len(files)
Replace signals with new style signals and connections¶
self.emit(SIGNAL("valuesChanged(const QStringList &)"), self.getArguments())
class Test(): valuesChanged = QtCore.pyqtSignal(list) def yourmethod(): self.valuesChanged.emit(self.getArguments)
Vector layer API changes¶
QgsFeatureRequest replaces select()¶
In QGIS 1.8 features are selected from a vector layer by using QgsVectorLayer.select() and then loop over provider.nextFeature(). In QGIS 2.0 the selection is defined by a QgsFeatureRequest object and features are retrieved using a python iterator created by QgsVectorLayer.getFeatures(QgsFeatureRequest). The QgsFeatureRequest object is only required to add selection criteria to the request - otherwise it can be omitted and all features will be returned.
layer.select() f=QgsFeature() while layer.nextFeature(f): ....
for f in layer.getFeatures(): ...
To add criteria to the selection you need to explicitly define a QgsFeatureRequest, for example
request=QgsFeatureRequest() request.setFilterRect(areaOfInterest) for f in layer.getFeatures(request): ...
Other criteria and be set using setSubsetOfFields and setFlags...
request.setSubsetOfFields([0,2]) # Only return selected fields request.setSubsetOfFields(['name','id'],layer.pendingFields()) # More user friendly version request.setFlags( QgsFeatureRequest.NoGeometry ) # Don't return geometry objects
Getting/setting QgsFeature attributes simplified¶
Feature attributes can be get and set by index, for example
index = layer.fieldNameIndex(fieldname) layer.select() f = QgsFeature() while layer.nextFeature(inFeat): fieldvalue=f.attributeMap()[index].toString())
for f in layer.getFeatures(): fieldvalue=f[fieldname]
Feature attributes can also be set by index, for example:
fields=layer.pendingFields() f = QgsFeature(fields) f['name']='Bruce' f['id']=42
NOTE: Do not use f=QgsFeature(layer.pendingFields()) - this will kill QGIS. The QgsFieldList returned by layer.pendingFields() must have at least the same lifetime as the QgsFeature.
Plugin repository and metadata changes¶
The plugin should include a metadata.txt file to upload to the repository. For example:
name=My Plugin description=Does useful stuff category=Plugins version=1.0 experimental=False qgisMinimumVersion=2.0 author=My name email@example.com icon=./plugin.png
NOTE: There was a rumor you should include a qgisMaximumVersion tag to the metadata.txt. Normally you don't need to set it. For further details see Plugin_Compatibility
Plugin init.py file should contain only the classFactory() method, all other information is in metadata.txt. ALL other members should be deleted from init.py .
Making a plugin compatible with all QGIS versions¶
If you really want to do it, set qgisMinimumVersion to 1.0 and qgisMaximumVersion to 2.99 explicitly. This way you can overwrite the default maximum version that is floor(qgisMinimumVersion) + 0.99.
Testing for QGIS version¶
if QGis.QGIS_VERSION_INT < 10900: # Use the old API style else: # Use the new API style
Testing for SIP api version (QGIS 2 uses SIP api v2)¶
import sip if sip.getapi("QVariant") > 1: # Use the new API style else: # Use the old API style
Note: This is not a recommend pattern except for small plugins as it will make your code complicated to read and maintain.