本文介绍了QGIS PyQt4 缺少 QString 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 QGIS Python 控制台中使用 QString.

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

from PyQt4.QtCore import QString

但它说:

ImportError: cannot import name QString

在我的 Python IDLE 中它运行良好,但我知道 QGIS 带来了它自己的 PyQt4.这里可能有什么问题?我能解决吗?

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()

from PyQt4 import QtCore
QtCore.QString()

无论如何都行不通.

我正考虑将 QtCore4.dll 从我自己的 PyQt4 安装复制到 QGIS,但 QGIS 使用 QtCore.prl 和 QtCore4.lib 而不是 QtCore.pyd 和 QtCore4.dll,就像我的 PyQt4 安装所使用的一样

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

当我在 QGIS 控制台中调用 help(PyQt4.QtCore) 时,它没有说明 QString 类,而 Python IDLE 中的操作也是如此......这真的很令人沮丧..

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 :)

推荐答案

如果 Python2 与 PyQt4 一起使用,那么 QStringQVariant 等类将默认可用.但是,Python3 的默认设置是消除这些类并改用等效的 Python 类型.

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.

可以使用 sip 模块覆盖这些默认值,如下所示:

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

如果 QString 在 QGIS 中不可用,要么是因为它使用的是 Python3,要么是因为它使用的是 Python2 并按照上面的建议切换 API.

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.

无论哪种方式,解决您的问题的最简单方法可能是运行 Python3 版本的 IDLE,这样您就不必再为 QStringQVariant 烦恼.

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.

请注意,在 PyQt5 中,没有切换 API 的选项,因此 QString 永远不会在那里可用.

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

还要注意,Qt4 的官方支持将于今年结束.因此,如果您希望新的 PyQt 应用程序面向未来,您的首选应该是 PyQt5 + Python3,除非您有充分的理由不这样做(例如不可避免的依赖项).

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

这篇关于QGIS PyQt4 缺少 QString 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 08:44