博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
TypeError: PyQt4.QtCore.QVariant python3.x
阅读量:7235 次
发布时间:2019-06-29

本文共 7793 字,大约阅读时间需要 25 分钟。

hot3.png

Python plugin API changes from 1.8 to 2.0

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.

Also see this page for changes in API not strictly related to Python .

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.

QVariant removed

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.

Remove all:

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:

Before:

value,ok = variantValue.toDouble()if not ok:    handleError()

After:

# 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: .

Before:

settings.value(“/yourboolsetting”, True).toBool()  settings.value(“/yourintsetting”, 10).toInt()[0]  settings.value(“/yourintsetting”).toByteArray()

After:

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.

Before:

yourstring.right(4)  files.join(",")  if yourstring.length() > 4:  if yourstring.isEmpty()

After:

yourstring[4:]  ",".join(files)  if len(yourstring) > 4  if not yourstring

Replace QStringList with list

Before:

mystrings = QStringList()

After:

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.

Before:

myvalue = QVariant(10)  myvalue = QVariant("Hello World")

After:

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

Before:

if files.isEmpty()  files.count()

After:

if not files  len(files)

Replace signals with new style signals and connections

Emitting before:

self.emit(SIGNAL("valuesChanged(const QStringList &)"), self.getArguments())

After:

class Test():    valuesChanged = QtCore.pyqtSignal(list)    def yourmethod():      self.valuesChanged.emit(self.getArguments)

Connecting before:

QObject.connect(self.iface,SIGNAL('projectRead ()'),self.readSettings)

After:

self.iface.projectRead.connect(self.readSettings)

Vector layer API changes

QgsFeatureRequest replaces select(), featureAtId()

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.

In the same way, use QgsFeatureRequest to change use of featureAtId() layer method.

Before:

layer.select()    f=QgsFeature()    while layer.nextFeature(f):       ....

After:

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

Before:

index = layer.fieldNameIndex(fieldname)    layer.select()    f = QgsFeature()    while layer.nextFeature(inFeat):        fieldvalue=f.attributeMap()[index].toString())

After:

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 Plugindescription=Does useful stuffcategory=Pluginsversion=1.0experimental=FalseqgisMinimumVersion=2.0author=My nameemail=myemail@somewhere.comicon=./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 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 styleelse:    # Use the new API style

Testing for SIP api version (QGIS 2 uses SIP api v2)

import sipif sip.getapi("QVariant") > 1:    # Use the new API styleelse:    # Use the old API style

转载于:https://my.oschina.net/dddttttt/blog/418674

你可能感兴趣的文章
hdfs的shell命令
查看>>
配置vue-devtools调试工具
查看>>
【酷熊科技】工作积累 ----------- Unity3D button 回调事件
查看>>
程序员修炼之道读后感2
查看>>
几个常见移动平台浏览器的User-Agent
查看>>
IOS 数据存储之 FMDB 详解
查看>>
纯数学教程 Page 324 正项级数绝对收敛的一种判别法
查看>>
关于键保留表的一些汇总
查看>>
python全栈开发 * 29知识点汇总 * 180712
查看>>
电源磁珠选择
查看>>
Android线控的使用
查看>>
《C陷阱与缺陷》阅读笔记(个人版)
查看>>
项目管理过程 (1)
查看>>
hdu 3033
查看>>
Redis (windows)安装
查看>>
Axure基础操作
查看>>
<转>boost 1.53 and STLPort build binary for windows
查看>>
洛谷 P1736 创意吃鱼法 Label:dp || 前缀和
查看>>
物理备库互转快照备库
查看>>
SEO之HTML标签
查看>>