TypeError: PyQt4.QtCore.QVariant python3.x

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 API_changes_for_version_20.

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: http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html.

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 Plugin
description=Does useful stuff
category=Plugins
version=1.0
experimental=False
qgisMinimumVersion=2.0
author=My name
[email protected]
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 seePlugin_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
时间: 2024-10-13 18:17:28

TypeError: PyQt4.QtCore.QVariant python3.x的相关文章

PyQt4.11.3(python3.4+QT4)ui文件生成py文件

最近开始接触学习Python,所以想用QT弄个窗体程序出来玩玩,环境是Python3.4.2.PyQt4.11.3-Py3.4.Win7.用PyQt自带的Designer设计出一个窗体ui文件后,需要转换为py文件方便Python程序中使用,在网上找了很多方法都不行,给我折腾了半天.现贴出测试可用的方法,希望大家不要像我一样走弯路,浪费了时间. 首先进入windows的命令提示符窗口,然后进入PyQt的uic文件夹,我的是D:\Program Files\python342\Lib\site-p

Pyqt QComboBox 省市区县联动效果

在Qt中, QComboBox方法窗口组件允许用户从列表清单中选择,在web中就是select标签,下拉选项. 省市区县的联动就是currentIndexChanged 获取当前的Index,通过这个索引在获取用户自定义的 QVariant auserData 获取这个Data后请求该父类pid为当前Data的词典key与value 下面详细讲述过程: 一.先用Qt Designer 画出界面 保存Qt Designer生成的文件为comboselect.ui, 其实这个ui文件就是XML文件,

python3 使用py2exe打包exe

py2exe在sourceforge 的下载只支持到2.7. 针对python3.0+的版本,需要自己编译. 1.下载源码 svn checkout svn://svn.code.sf.net/p/py2exe/svn/trunk py2exe-svn 2.编译环境 这里使用的是vs2014. 3.安装 进入py2exe-3 python setup.py install 这里会进行编译.安装. 此外,python默认使用的是vs9,针对vs2014,需要改下文件: Lib\distutils\

python列表和QVariant

pyqt中,要给QAbstractTableModel的setData函数传递一个list参数: [20,'00:00:19'] 涉及到QVariant和list的转换. 可以使用QVariant类中的toPyObject是转换. 环境是:Python 2.7.6 pyqt4 4.8.6 有文章说是,toPyObject只能转换字符串,而且只能转换字典. 测试一下,支持数字,支持字典和列表. #coding:utf-8 from PyQt4.QtCore import QVariant a={2

PyQt4 HardwareManager

# PyQt4 HardwareManager # 声明: # 本软件主要是由于朋友说想要一个产品缺陷记录软件,主要用于记录产品缺陷, # 通过产品序列号进行插入.查询,本来想用VC++ 6.0做,但是每次打开开发环境就 # 奔溃了,所以只能换一个开发环境,于是尝试用PyQt4进行原型开发,在开发过程中 # 发现,这确实是一个很好的思路,该软件可以换一种思路用于其他环境下,但就 # 目前而已,这仅仅是一个原型. # # 2015-10-23 晴 深圳 南山平山村 曾剑锋 \\\\\\\\\\\\

python3用pyqt5开发简易浏览器

http://python.jobbole.com/82715/ 在这篇教程中,我们会用 Python 的 PyQt 框架编写一个简单的 web 浏览器.关于 PyQt ,你可能已经有所耳闻了,它是 Qt 框架下的一系列 Python 组件,而 Qt(发音类似"cute")是用来开发 GUI 的 C++ 框架.严格来讲, Qt 也可用于开发不带图形界面的程序,但是开发用户界面应该是 Qt 框架最为广泛的应用了.Qt 的主要优势是可以开发跨平台的图形界面程序,基于 Qt 的应用能够借助于

PYQT4.12

from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4.QtCore import (QDate, QFile, QFileInfo, QIODevice, QString, QStringList, QDir, QTextStream, Qt, SIGNAL) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) startDir = QS

用 pyqt4 编写的一个翻译小工具

有时候我们在开发时遇到一些陌生的英文单词或者不容易看出某些长句的中文意思时该怎么办呢?打开桌面上的翻译软件?打开浏览器里收藏着的翻译网址或者直接贴上百度的搜索框去查?这些方法固然可以,还很常见,但如果是 linux 系统的话,很难找到像 windows 上那些公司级别来开发的成熟的翻译软件,所以只能打开浏览器来查了.浏览器一般都会装上一些翻译插件,比如我常用的 chrome 的 划词翻译,直接用这些插件来进行翻译比起打开一个翻译网站或者百度google搜索要更快,毕竟因为加载的内容更少,但这终究

PYQT4.14

# -*- coding: utf-8 -*- from PyQt4.QtGui import * from PyQt4.QtCore import * import sys QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8")) class Palette(QDialog): def __init__(self,parent=None): super(Palette,self).__init__(parent) self.s