12

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
reckless
  • 741
  • 12
  • 53
  • @ekhumoro yes that solves the problem. Would you like to turn your comment into an answer so I can mark this question as solved? – reckless Aug 26 '19 at 20:03

1 Answers1

18

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336