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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM