2015-01-09 46 views
2

我试图将一个基于PyQt的应用程序移植到Python 3.如果我用sys.argv初始化QApplication,QApplication.arguments()会返回那些没有非-ascii字符。解决方法是将参数作为字节进行编码。但我很难相信这是最好的方法。为什么PyQt不能接受unicode字符串?也许一些区域设置需要调整?python3-qt4在QApplication构造器中丢弃unicode字符串中的非ASCII字符

示例代码:

#! /usr/bin/python3 

from PyQt4.QtGui import QApplication 

args = ["test", "tsch\u00fcss", "tsch\u00fcss".encode("utf-8")] 
print("args:", args) 
qapp = QApplication(args) 
qargs = qapp.arguments() 
print("qargs:", qargs) 

输出:

args: ['test', 'tschüss', b'tsch\xc3\xbcss'] 
qargs: ['test', 'tschss', 'tschüss'] 

东西,让没有区别:

import sip 
sip.setapi("QString", 2) 

import locale 
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 

Ubuntu的14.10,python3-PyQt4的4.11.2 + DFSG-1

回答

2

这看起来像一个错误我PyQt,由PySide正确处理。

而且似乎没有理由ARGS不能正确地传递给应用程序构造函数之前编码:

>>> import os 
>>> from PyQt4 import QtCore 
>>> args = ['føø', 'bær'] 
>>> app = QtCore.QCoreApplication([os.fsencode(arg) for arg in args]) 
>>> app.arguments() 
['føø', 'bær'] 

如果你想看到这个拿不动,请在PyQt Mailing List报告。

+0

我刚刚报告了这个错误。至于PySide,它并不好。在Python 3中,字节参数被完全丢弃。在Python 2中,unicode参数会导致解释器崩溃。 – proski 2015-01-12 21:18:28

+0

'os.fsencode'在Python 2中不可用。我希望代码在没有条件的情况下在Python 2和3中工作。 – proski 2015-01-12 21:27:07

+1

@proski。使用PySide-1.2.2和Python 3与unicode工作正常。这不是unicode不适用于Python 2(无论是PySide还是PyQt4)的错误,因为字节应始终是唯一有效的输入。出于同样的原因,Python 2中缺少'os.fsencode'是无关紧要的。如果你想要Python 2和Python 3之间的兼容性,你将不得不自己处理这个问题。这里唯一的错误是PyQt不能正确处理Python 3的unicode字符串。 – ekhumoro 2015-01-13 00:46:46