Search code examples
pythonpython-3.xstringpyside2qbytearray

How to convert a QByteArray to a python string in PySide2


I have a PySide2.QtCore.QByteArray object called roleName which I got encoding a python string:

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

How can I get my decoded string back?


Solution

  • In Python3, you must specify an encoding when converting a bytes-like object to a text string. In PySide/PyQt, this applies to QByteArray in just the same way as it does with bytes. If you don't specify and encoding, str() works like repr():

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

    There are several different ways to convert to a text string:

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

    The last example is specific to QByteArray, but the first two should work with any bytes-like object.