等同于 PyQt5 中的 QString.fromLocal8Bit 方法

Equivalent to QString.fromLocal8Bit method in PyQt5

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

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

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

Qt uses the QString class to represent Unicode strings, and the QByteArray to represent byte arrays or strings. In Python v3 the corresponding native object types are str and bytes.

但是没有解释对应的Qt 类(QString,QByteArray)的方法是如何替换的。

作为 the documentation explains, in PyQt5, QString is automatically converted to a str (Python 3) or unicode (Python 2) 对象。因此,这些 Python 类型提供的任何功能都是 "replaced" 方法。 QByteArray class 保持不变。

如果您知道您的消息数据编码为 UTF-8,则最简单的 C++ 代码行是:

messageString = bytes(aMultiformMessage).decode()

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

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

如果你真的想要 local 编码,你可以从 locale 模块中使用 getpreferredencoding(). However, it may be simpler to take the Qt route, and use the QTextCodec class:

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

这正是 fromLocal8bit() 用来将 QByteArray 转换为 QString 的方法。 (请注意,这种方法是 thread-safe,而 getpreferredencoding 可能并不总是如此)。