3

This one is a pickle. I'm trying to save my window/other elements to json format so that I can have multiple data stored in 1 place for my window/etc

I know that QByteArray has these functions: std::string QByteArray::toStdString() const and QByteArray QByteArray::fromStdString(const std::string &str)

Which should allow me to do it but so far I can't get it to work in Python. Some info about I found here (C) > Correct way to losslessly convert to and from std::string and QByteArray

I tried doing something like this:

print(self.saveGeometry())
bar = self.saveGeometry()
print(bytes(str(bar).encode()))

to convert QByteArray to bytearray that then I could save as string but I'm getting

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd9 in position 1: invalid continuation byte

Can any1 suggest how can I use either the native QT5 5.4+ function to save QByteArray to QByteArray.toStdString to json then load json > to QByteArray.fromStdString > to geometry or other method ?

Thanks!

Dariusz
  • 960
  • 13
  • 36

1 Answers1

10

JSON cannot serialize bytes/bytearray objects, so you need to convert them to unicode objects instead. That means it's necessary to somehow "decode" the raw bytes data contained in the QByteArray. One way to do this is to convert the bytes to some ascii-compatible format first, so as to avoid any unicode errors:

>>> g = widget.saveGeometry()
>>> d = json.dumps(bytes(g.toHex()).decode('ascii'))
>>> x = QByteArray.fromHex(bytes(json.loads(d), 'ascii'))
>>> x == g
True
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Awesome thanks! I got as far as toHex(), but could not get it to work, thank you so much for that answer! – Dariusz May 30 '17 at 17:32