问题
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