PyQt4:在 trUtf8 字符串中检测到非 ASCII 字符 [英] PyQt4: Non-ASCII character detected in trUtf8 string
问题描述
我想弄清楚如何为 PyQt tr()
或 trUtf8()
函数提供 UTF-8 文本.
I'm trying to figure out how to feed the PyQt tr()
or trUtf8()
functions UTF-8 text.
以下是字符串示例:
self.tr('λληνικά')
self.tr(u'εληνικά')
self.tr('ελνικά'.encode('utf-8'))
self.tr(u'ελληικά'.encode('utf-8'))
self.trUtf8('λληνικ')
self.trUtf8(u'εληνιά')
self.trUtf8('ελνι'.encode('utf-8'))
self.trUtf8(u'ελλκά'.encode('utf-8'))
带有 self.tr
的那些在 Qt Linguist 中显示为乱码.带有 self.trUtf8
的显示正常,但在应用 pylupdate4
时会触发警告:
The ones with self.tr
display as gibberish in Qt Linguist. The ones with self.trUtf8
display fine, but they trigger a warning when applying pylupdate4
:
Non-ASCII character detected in trUtf8 string
前导 u 和 .encode('utf-8')
似乎没有任何区别,至少在解析时(使用 pylupdate4
).
The leading u and the .encode('utf-8')
don't seem to make any difference, at least at parsing time (using pylupdate4
).
正确的方法是什么?
我也想知道这条线的作用:
I'm also wondering about the role of this line:
QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("utf-8"))
但我知道它对 pylupdate4
的文件解析没有影响,它只能在执行时产生影响.
But I know it has no effect on file parsing by pylupdate4
, it could only make a difference at execution time.
推荐答案
tr
和 trUtf8
的区别在于,后者明确声明编码为 UTF-8
.
The difference between tr
and trUtf8
, is that the latter explicitly declares that the encoding is UTF-8
.
就其本身而言,tr
不暗示字符串的编码,因此您只能将其传递为 ascii 字符串,或者使用 setCodecForTr
.但正如您猜测的那样,这只会在运行时产生影响.为了使 pylupdate
也使用该编码,您需要在 pro 文件中设置相应的变量:
On its own, tr
implies nothing about the encoding of the string, and so you either must only ever pass it ascii strings, or explicitly set an appropriate encoding using setCodecForTr
. But as you surmised, that will only have an effect at runtime. In order for pylupdate
to also use that encoding, you need to set a corresponding variable in the pro file:
CODECFORTR = UTF-8
SOURCES = source.py
TRANSLATIONS = translation.ts
(似乎 pylupdate
将假定没有它的 latin-1
编码,因此该编码中不可用的任何字符最终都会成为 mojibake).
(It seems that pylupdate
will assume a latin-1
encoding without that, so any characters not available in that encoding will end up as mojibake).
至于警告消息:它们可能是为了反映 有关可移植性问题的 trUtf8 的 Qt 文档.
As for the warnings messages: they are probably there to reflect the corresponding warnings in the Qt docs for trUtf8 regarding portability issues.
最好的方法是使用 tr
并将编码显式设置为 UTF-8
.trUtf8
函数在 Qt4 中实际上已过时.它甚至在 Qt5 中都不存在,它假定所有内容都使用 UTF-8
- 所以最终你甚至不需要显式设置编码.
The best way to proceeed is to use tr
and explicitly set the encoding to UTF-8
. The trUtf8
function is effectively obsolete in Qt4. It doesn't even exist in Qt5, which assumes UTF-8
for everything - so eventually you won't even need to explicitly set the encoding.
这篇关于PyQt4:在 trUtf8 字符串中检测到非 ASCII 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!