I am looking for a way to replace the following C++ line with PyQt5 code:
QString messageString = QString::fromLocal8Bit(aMultiformMessage.data(), aMultiformMessage.size());
where aMultiformMessage
is a QByteArray.
Any Ideas? The PyQt5 Documentation (in Things to be aware of) only states that:
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.
But it doesn't explain how the methods of the corresponding Qt classes (QString, QByteArray) are replaced.
As the documentation explains, in PyQt5, QString is automatically converted to a str
(Python 3) or unicode
(Python 2) object. So the methods are "replaced" by whatever functionality is provided by those Python types. The QByteArray class remains unchanged.
If you know that your message data is encoded as UTF-8, the simplest equivalent to your C++ line of code would be:
messageString = bytes(aMultiformMessage).decode()
However, if some other encoding is used, you can specify it explicitly:
messageString = bytes(aMultiformMessage).decode('latin-1')
If you really want the local encoding, you can get it from the locale
module by using getpreferredencoding(). However, it may be simpler to take the Qt route, and use the QTextCodec class:
messageString = QTextCodec.codecForLocale().toUnicode(aMultiformMessage)
This is exactly what fromLocal8bit()
uses to convert a QByteArray
to a QString
. (And note that this approach is thread-safe, whereas getpreferredencoding
may not always be so).