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

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

转载于:https://www.cnblogs.com/msec23/archive/2012/12/20/2826866.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值