Incompatibility between Python 3.2 and Qt?

不打扰是莪最后的温柔 提交于 2019-12-21 06:19:14

问题


I have problems with Python 3.2 and PyQt 4.8.6 It seems as if Python 3.2 can`t find the imports. Especially the "Q"-methods. For example the QString below.

from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

With Python 2.7 everything works fine. Where is the mistake in my code?


回答1:


Python3 made many incompatible changes in order to "clean up" the language, and, to a certain extent, PyQt has done the same by introducing "more pythonic" versions of some APIs. But these different API versions can be selected on a class by class basis for both Python2 and Python3, so the only real difference is the defaults chosen for each Python version.

In Python2, the default API version for QString is "v1", which implements it as a Python type; in Python3 the default is "v2", which automatically converts to and from the appropriate Python string object.

The API version can be selected by using the setapi function from the sip package. So to continue using the QString class in your application, just make sure the appropropriate version is set before the PyQt modules are first imported:

import sip
sip.setapi('QString', 1)

from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

For details of all the APIs that can be set this way, see here.




回答2:


Take a look at the notes about Python 3 in the PyQt Reference Guide.

The QString class is implemented as a mapped type that is automatically converted to and from a Python string. In addition a None is converted to a null QString. However, a null QString is converted to an empty Python string (and not None). (This is because Qt often returns a null QString when it should probably return an empty QString.)

I've not moved any code over to Python 3 yet, but I believe that the idea is to use normal Python strings instead of QStrings. PyQt will accept them and they already support unicode in Python 3. Where normally a PyQt function would return a QString it will return a regular python string under Python 3.

Have a look at the other differences on the linked page too.



来源:https://stackoverflow.com/questions/8307985/incompatibility-between-python-3-2-and-qt

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