QGIS PyQt4 missing QString class

百般思念 提交于 2019-12-31 02:26:12

问题


i was trying to use a QString in the QGIS Python Console.

from PyQt4.QtCore import QString

but it says:

ImportError: cannot import name QString

In my Python IDLE it works fine, but i know that QGIS brings its own PyQt4. What could be the problem here? And could i solve it?

import PyQt4.QtCore
PyQt4.QtCore.QString()

and

from PyQt4 import QtCore
QtCore.QString()

dosen't works anyway.

I was thinking about to copy the QtCore4.dll from my own PyQt4 installation to QGIS, but QGIS uses QtCore.prl and QtCore4.lib instead of QtCore.pyd and QtCore4.dll, like it is used by my PyQt4 installation

When i call help(PyQt4.QtCore) in the QGIS Console it says nothing about a QString class, while same the action in Python IDLE does... it's really frustrating..

Would be great if somebody know what to do :)


回答1:


If Python2 is used with PyQt4, then classes like QString and QVariant will be available by default. However, the default for Python3 is to eliminate these classes and use the equivalent python types instead.

These defaults can be overridden by using the sip module, like this:

import sip
# switch on QString in Python3
sip.setapi('QString', 1)

# switch off QString in Python2
sip.setapi('QString', 2)

from PyQt4 import QtCore

If QString is not available in QGIS, it's either because it's using Python3, or because it's using Python2 and switching APIs as suggested above.

Either way, probably the simplest fix for your issue would be to run the Python3 version of IDLE, so that you no longer have to bother with QString and QVariant.

Note that in PyQt5, there is no option to switch APIs, and so QString will never be available there.

And also note that official support for Qt4 ends this year. So if you want to future-proof a new PyQt application, your first choice should be PyQt5 + Python3, unless you have good reasons for doing otherwise (e.g. unavoidable dependencies).




回答2:


I've not used QGIS, but this is probably because the PyQt has been switched to the new API version 2 (see http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html). In the new API, any Qt function returning or taking a QString takes a Python native string instead. The new API is much more convenient and is the default for PyQt5.



来源:https://stackoverflow.com/questions/28632169/qgis-pyqt4-missing-qstring-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!