【问题标题】:Equivalent to QString.fromLocal8Bit method in PyQt5等效于 PyQt5 中的 QString.fromLocal8Bit 方法
【发布时间】:2018-08-29 12:19:16
【问题描述】:

我正在寻找一种用 PyQt5 代码替换以下 C++ 行的方法:

QString messageString = QString::fromLocal8Bit(aMultiformMessage.data(), aMultiformMessage.size());

aMultiformMessage 是一个 QByteArray。 有任何想法吗? PyQt5 文档(Things to be aware of)仅声明:

Qt 使用 QString 类来表示 Unicode 字符串,并且 QByteArray 来表示字节数组或字符串。在 Python v3 中 对应的原生对象类型为 str 和 bytes。

但是并没有说明对应的Qt类(QString、QByteArray)的方法是如何替换的。

【问题讨论】:

  • 原生 Python 方式类似于messageString = aMultiformMessage.data().decode("latin-1")。将str 传递给PyQt5 方法时,会隐式转换为QString

标签: python-3.x pyqt5 porting qstring qbytearray


【解决方案1】:

作为 the documentation explains,在 PyQt5 中,QString 会自动转换为 str (Python 3) 或 unicode (Python 2) 对象。因此,这些方法被这些 Python 类型提供的任何功能“替换”。 QByteArray 类保持不变。

如果您知道您的消息数据被编码为 UTF-8,那么与您的 C++ 代码行等效的最简单的代码是:

messageString = bytes(aMultiformMessage).decode()

但是,如果使用了其他编码,您可以明确指定它:

messageString = bytes(aMultiformMessage).decode('latin-1')

如果你真的想要 local 编码,你可以使用getpreferredencoding()locale 模块中获取它。不过,走 Qt 路线可能更简单,使用QTextCodec 类:

messageString = QTextCodec.codecForLocale().toUnicode(aMultiformMessage)

这正是fromLocal8bit() 用来将QByteArray 转换为QString 的方法。 (请注意,这种方法是线程安全的,而getpreferredencoding 可能并非总是如此)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 2012-01-14
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多