【问题标题】:How to convert a QByteArray to a python string in PySide2 [duplicate]如何在 PySide2 中将 QByteArray 转换为 python 字符串 [重复]
【发布时间】:2019-12-30 22:58:02
【问题描述】:

我有一个名为roleNamePySide2.QtCore.QByteArray 对象,我得到了一个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

我怎样才能找回我解码的字符串?

【问题讨论】:

  • @ekhumoro 是的,可以解决问题。您想将您的评论转化为答案,以便我将此问题标记为已解决吗?

标签: python python-3.x string pyside2 qbytearray


【解决方案1】:

在 Python3 中,将字节类对象转换为文本字符串时必须指定编码。在 PySide/PyQt 中,这适用于 QByteArray,其方式与 bytes 相同。如果你不指定和编码,str() 就像repr() 一样工作:

>>> ba = Qt.QByteArray(b'foo')
>>> str(ba)
"b'foo'"
>>> b = b'foo'
>>> str(b)
"b'foo'"

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

>>> str(ba, 'utf-8') # explicit encoding
'foo'
>>> bytes(ba).decode() # default utf-8 encoding
'foo'
>>> ba.data().decode() # default utf-8 encoding
'foo'

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

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 2016-08-04
    • 2018-06-11
    • 2018-08-31
    • 2020-10-27
    • 2021-08-16
    • 1970-01-01
    相关资源
    最近更新 更多