GVKun编程网logo

TypeError: PyQt4.QtCore.QVariant python3.x

18

想了解TypeError:PyQt4.QtCore.QVariantpython3.x的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于DifferencesBetweenPyQt4an

想了解TypeError: PyQt4.QtCore.QVariant python3.x的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于Differences Between PyQt4 and PyQt5、gyp ERR! configure error gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys、ImportError:无法从“ PyQt4”导入名称“ QtCore”、PyCharm中PyQt4的Qt和QtCore代码提示不能用的新知识。

本文目录一览:

TypeError: PyQt4.QtCore.QVariant python3.x

TypeError: PyQt4.QtCore.QVariant python3.x

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(), featureAtId()
  • 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.

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=myemail@somewhere.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 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

Differences Between PyQt4 and PyQt5

Differences Between PyQt4 and PyQt5

Differences Between PyQt4 and PyQt5

PyQt5 is not compatibile with PyQt4 (although experience shows that the effort in porting applications from PyQt4 to PyQt5 is not great). This section describes the main differences between the two.

Supported Python Versions

Versions of Python earlier than v2.6 are not supported.

Deprecated Features

PyQt5 does not support any parts of the Qt API that are marked as deprecated or obsolete in Qt v5.0. However it is possible that some of these have been included accidentaly. These are considered bugs and will be removed if found.

Multiple APIs

PyQt4 supports a number of different API versions (QStringQVariant etc.). With the exception of QVariant, PyQt5 only implements v2 of those APIs for all versions of Python. The changed support for QVariant, including the removal of QPyNullVariant, is described in Support for QVariant.

Old-style Signals and Slots

PyQt4’s old-style signals and slots are not supported. Therefore the following are not implemented in PyQt5:

All methods that had arguments that are usually the results of calls to SIGNAL() or SLOT() are no longer supported. There will always be an equivalent that takes a bound signal or callable respectively.

In addition the following methods have differences:

New-style Signals and Slots

Qt implements signals with an optional argument as two separate signals, one with the argument and one without it. PyQt4 exposed both of these allowing you to connect to each of them. However, when emitting the signal, you had to use the signal appropriate to the number of arguments being emitted.

PyQt5 exposes only the signal where all arguments are specified. However it allows any optional arguments to be omitted when emitting the signal.

Unlike PyQt4, PyQt5 supports the definition of properties, signals and slots in classes not sub-classed from QObject (i.e. in mixins).

QtDeclarativeQtScript and QtScriptTools Modules

PyQt4’s QtDeclarativeQtScript and QtScriptTools modules are not supported. These have been replaced by PyQt5’s QtQml and QtQuick modules. Unlike PyQt4, PyQt5 supports the creation of Python objects from QML.

QtGui Module

PyQt4’s QtGui module has been split into PyQt5’s QtGuiQtPrintSupport and QtWidgets modules.

QtOpenGL Module

Only the QGLContextQGLFormat and QGLWidget classes are supported by PyQt5.

QtWebKit Module

PyQt4’s QtWebKit module has been split into PyQt5’s QtWebKit and QtWebKitWidgets modules.

QtXml Module

PyQt4’s QtXml module is not supported. Use either the QXMLStreamReader and QXMLStreamWriter classes or Python’s standard XML modules.

pyqtconfig Module

PyQt4’s pyqtconfig module is not supported. The section The PyQt5 Extension API describes the support that PyQt5 provides to third-party packages (e.g. QScintilla) that want to build on top of PyQt5.

dbus.mainloop.qt Module

PyQt4’s dbus.mainloop.qt module is called dbus.mainloop.pyqt5 in PyQt5. This allows them to be installed side by side. Their functionality is identical.

QDataStream

The readUInt8()readInt8()writeUInt8() and writeInt8() methods all interpret the values being read and written as numeric values. In PyQt4 they are interpreted as single character strings.

QFileDialog

The getOpenFileNameAndFilter()getOpenFileNamesAndFilter() and getSaveFileNameAndFilter() methods of PyQt4’s QFileDialog have now been renamed getOpenFileName(),getOpenFileNames() and getSaveFileName() respectively in PyQt5. PyQt4’s implementations of getOpenFileName()getOpenFileNames() and getSaveFileName() are not supported in PyQt5.

QGraphicsItemAnimation

Support for the deprecated QGraphicsItemAnimation class has been removed. If porting an existing PyQt4 application then consider first updating it to use QPropertyAnimationinstead.

QMatrix

Support for the deprecated QMatrix class has been removed. If porting an existing PyQt4 application then consider first updating it to use QTransform instead.

QPyTextObject

PyQt4 implements the QPyTextObject as a workaround for the inability to define a Python class that is sub-classed from more than one Qt class. PyQt5 does support the ability to define a Python class that is sub-classed from more than one Qt class so long as all but one of the Qt classes are interfaces, i.e. they have been declared in C++ as such usingQ_DECLARE_INTERFACE. Therefore QPyTextObject is not implemented in PyQt5.

QSet

In PyQt4, QSet was implemented as a list in Python v2 and a set in Python v3. In PyQt5 QSet is always implemented as a set.

pyuic5

pyuic5 does not support the --pyqt3-wrapper flag of pyuic4.

pyrcc5

pyrcc5 does not support the -py2 and -py3 flags of pyrcc4. The output of pyrcc5 is compatible with all versions of Python starting with Python v2.6.

Cooperative Multi-inheritance

Unlike PyQt4, PyQt5 classes implement cooperative multi-inheritance. In other words PyQt5 classes always do the equivalent of the following Python v3 code in their __init__methods (where kwds is a dictionary of unused keyword arguments):

super().__init__(**kwds)

This means that those unused keyword arguments are passed to the __init__ methods of any mixin classes. Those mixin classes must cooperate, i.e. they must make a similar call if they have their own __init__ implementations.

When using multiple inheritance in PyQt4 it is common to call the __init__ methods of the super-classes explicitly, for example:

class MyQObject(QObject, MyMixin):
    def __init__(self, parent, mixin_arg):
        QObject.__init__(self, parent)
        MyMixin.__init__(self, mixin_arg)

        # Other initialisation...

In PyQt5 the above would cause MyMixin.__init__ to be called twice. Instead it should be implemented as follows:

class MyQObject(QObject, MyMixin):
    def __init__(self, **kwds):
        super().__init__(**kwds)

        # Other initialisation...

Note that if there is no other initialisation to do then the __init__ method isn’t actually needed.

The mixin class should be implemented as follows:

class MyMixin:
    def __init__(self, mixin_arg, **kwds):
        super().__init__(**kwds)

        # Other initialisation...

If a class only inherits from a single class then it can still call the super-class’s __init__ method explicitly (although it is recommended to use super()).

See Support for Cooperative Multi-inheritance.

Releasing the GIL

The GIL is only released when it is known to be needed. PyQt4 always released the GIL when calling Qt.

Object Destruction on Exit

When the Python interpreter exits PyQt4 (by default) calls the C++ destructor of all wrapped instances that it owns. This happens in a random order and can therefore cause the interpreter to crash. This behavior can be disabled by calling the sip.setdestroyonexit() function.

PyQt5 always calls sip.setdestroyonexit() automatically. However if the wrapped instances have not been created at the module level and have instead been created in a function then the problem will still exist. For example, do not do the following:

def main():
    app = QApplication(sys.argv)

    w = QWidget()
    w.show()

    app.exec()

if __name__ == '__main__':
    main()

Instead, do the following:

if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = QWidget()
    w.show()

    app.exec()

gyp ERR! configure error gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys

gyp ERR! configure error gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys

问题描述:

  1. //执行:   
    npm install --registry=https://registry.npm.taobao.org

    报错如下:

     

    解决方法:
    出现这个原因是因为node环境没有配置python安装路径

    1、首先找到windows本机python27(一定要是这个版本)安装路径(下图为本人python27安装路径)

    注意:本人报错是在npm install执行之后的,这个命令会默认在C盘下安装一个Python27的版本(如果你自己安装的有自己的python27可以使用自己的安装路径)

    2、执行:

    // 设置config
    npm config set python C:\Python27
    // 重新执行npm
    npm install
     

ImportError:无法从“ PyQt4”导入名称“ QtCore”

ImportError:无法从“ PyQt4”导入名称“ QtCore”

如何解决ImportError:无法从“ PyQt4”导入名称“ QtCore”?

我在manjaro上遇到此错误ImportError: cannot import name ''QtCore'' from ''PyQt4'',因此我尝试安装PyQt4,但出现此错误

/Scaricati/PyQt4_gpl_x11-4.12.3 $ python configure-ng.py Querying qmake about your Qt installation... Determining the details of your Qt installation... This is the GPL version of PyQt 4.12.3 (licensed under the GNU General Public License) for Python 3.8.5 on linux. Error: This version of PyQt4 and the commercial version of Qt have incompatible licenses.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

PyCharm中PyQt4的Qt和QtCore代码提示不能用

PyCharm中PyQt4的Qt和QtCore代码提示不能用

PyCharm中PyQt4的Qt和QtCore代码提示不能用,但是eclipse和IDLE就可以。有人就说了,那就用eclipse好了,但是我们应该发现问题就应该解决问题嘛!

1.eclipse可以

2.IDLE也行

3.这个貌似是导致代码提示失效的原因,如果是该怎么整呢?

4.还有OSC这里Ctrl+回车就发布问题容易点错!

我们今天的关于TypeError: PyQt4.QtCore.QVariant python3.x的分享已经告一段落,感谢您的关注,如果您想了解更多关于Differences Between PyQt4 and PyQt5、gyp ERR! configure error gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys、ImportError:无法从“ PyQt4”导入名称“ QtCore”、PyCharm中PyQt4的Qt和QtCore代码提示不能用的相关信息,请在本站查询。

本文标签: