如何在 PySide2 中将 QByteArray 转换为 python 字符串

dal*_*t97 9 python string python-3.x qbytearray pyside2

我有一个PySide2.QtCore.QByteArray对象叫做roleName我编码了一个 python 字符串:

propName = metaProp.name() // this is call of [const char *QMetaProperty::name() ](https://doc.qt.io/qt-5/qmetaproperty.html#name)
// encode the object
roleName = QByteArray(propName.encode())
print(roleName) // this gives b'myname'
// now I would like to get just "myname" without the "b" 
roleString = str(roleName)
print(roleString) // this gives the same output as above
Run Code Online (Sandbox Code Playgroud)

如何取回解码后的字符串?

ekh*_*oro 11

在 Python3 中,将类字节对象转换为文本字符串时必须指定编码。在 PySide/PyQt 中,这适用QByteArray于与bytes. 如果您不指定和编码,则str()工作方式如下repr()

>>> ba = Qt.QByteArray(b'foo')
>>> str(ba)
"b'foo'"
>>> b = b'foo'
>>> str(b)
"b'foo'"
Run Code Online (Sandbox Code Playgroud)

有几种不同的方法可以转换为文本字符串:

>>> str(ba, 'utf-8') # explicit encoding
'foo'
>>> bytes(ba).decode() # default utf-8 encoding
'foo'
>>> ba.data().decode() # default utf-8 encoding
'foo'
Run Code Online (Sandbox Code Playgroud)

最后一个示例特定于QByteArray,但前两个示例应该适用于任何类似字节的对象。