您的位置:首页 > 编程语言 > Python开发

PyQt与Python之间的字符转换(转)

2012-12-20 18:23 190 查看
GUI编程:
可以创建一个QTextEdit对象myTextEdit, 检验:
myTextEdit.append("中文")
或者
myTextEdit.append(u"中文")
或者
myTextEdit.append(QtCore.QString('中文'))
或者
myTextEdit.append(QtCore.QString(u'中文'))
你会发现显示都是乱码...因为它们都是默认按ascii编码进行内部转换得到QString相应utf16编码的。

解决方法是:
利用unicode()函数显示指定gb2312编码进行中文编码转换,转换后的Python Unicode object则是可以直接作为QString参数代入用的:

>>> unicode('中文', 'gb2312', 'ignore')
u'"u4e2d"u6587'
>>> print unicode('中文', 'gb2312', 'ignore')
中文
>>>

myTextEdit.append(unicode('中文', 'gb2312', 'ignore'))
#用以替代myTextEdit.append(u"中文")
或者多此一举下:
myTextEdit.append(QtCore.QString(unicode('中文', 'gb2312', 'ignore')))
#用以替代myTextEdit.append(QtCore.QString(u'中文'))

5. QString向Python string object和Python Unicode object的转换。

Python中需要用Python string object和Python Unicode object的地方可就不一定可以直接用QString了!!!
QString向Python string object转换可以理解,因为编码不同。
QString向Python Unicode object的转换?需要转换吗?不都是utf16编码吗?
QString是tuf16编码,但是它的实现并非Python Unicode object那样直接的utf16码,而实际是一个QChar串,每个QChar才对应unicode符,所以地位相当但并不相同。
许多英文书籍写到:可以使用str()函数直接将QString转换为Python string object,可以使用unicode()直接将QString转换为Python Unicode object。如《PyQt手册》:

In order to convert a QString to a Python string object use the Python str() builtin. Applying str() to a null QString and an empty QString both result in an empty Python string object.

In order to convert a QString to a Python Unicode object use the Python unicode() builtin. Applying unicode() to a null QString and an empty QString both result in an empty Python Unicode object.

但同样只适用于英文,具体见下面分别分析。
1)QString向Python Unicode object的转换。
>>> from PyQt4 import QtGui, QtCore
>>> unicode(QtCore.QString('def'))
u'def'
>>> print unicode(QtCore.QString('def'))
def

对于中文,unicode()必须要指定编码后有效。(这样也只针对直接的QString有效?对于Qt GUI编程中,从QWidget取得的QString无效?)

>>> from PyQt4 import QtGui, QtCore
>>> unicode(QtCore.QString('中文'))
u'"xd6"xd0"xce"xc4'
>>> print unicode(QtCore.QString('中文'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'gbk' codec can't encode character u'"xd6' in position 0: il
legal multibyte sequence

指定原始编码后:
>>> unicode(QtCore.QString('中文'),'gbk','ignore')
u'"u4e2d"u6587'
>>> print unicode(QtCore.QString('中文'),'gbk','ignore')
中文 TEST
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: