PySide- How to save a QByteArray to a file

Hey guys,

I’m getting the current state of my table view header via QHeaderView.saveState() which returns a QByteArray. I need to save that to a file, if possible a JSON, so it can be read back next time the user launch my tool (like saving a UI preferences file for each user)

How should I do that? I don’t know how to handle that kind of data. I tried converting QByteArray.toHex() and saving that as a string but it doesn’t work when I bring it back.

Thanks for all the help you can bring!!

Workaround solution, it deals with the QByteArray by itself:

To save:
settings = QtCore.QSettings(“userPrefs.ini”, QtCore.QSettings.IniFormat)
settings.setValue(“columnConfig”, QtCore.QHeaderView.saveState())

To read:
settings= QtCore.QSettings(“userPrefs.ini”, QtCore.QSettings.IniFormat)
QtCore.QHeaderView.restoreState(settings.value(“columnConfig”))

At least with PySide I think you can just pass the QByteArray into str()

At least this works for me when I test it in the console.


from PySide import QtCore
q_byte_array = QtCore.QByteArray('random bytes')

print str(q_byte_array)


Oh yeah, that works fine. Problem is I couldn’t find a way to bring that back from a file and make PySide accept it. That’s why I ended up using PySide own tools to save user settings and handle the QByteArray through there.

Ah okay, that makes a bit more sense.

So no clue about doing anything with json, like your original question asked.

But I was able to get a sort of test working saving out to a file.

Basically I just wrote it out to a file that I opened in binary mode, I also used a bytearray instead of a string on the basis that it should be safer for moving binary data around. Though I believe a string works just as well.


# This was using some super simple dialog with a table widget.
# Which is where the dialog object came from.
state = bytearray(dialog.tablewidget.verticalHeader().saveState())
with open('e:/tmp', 'wb') as fyle:
    fyle.write(state)

with open('e:/tmp', 'rb') as fyle:
    loads = fyle.readlines()

saved_state = QtCore.QByteArray(b'
'.join(loads))

# This should print True
print saved_state == dialog.tablewidget.verticalHeader().saveState()

# Also this seemed to work?
dialog.tablewidget.verticalHeader().restoreState(saved_state)


Though honestly your solution of using the QSettings is probably a better one overall.
It seems kind of nuts to try to build your own serialization system, especially when the built in one works.

But just in case anyone does need to write one of these things out to a file, I think the trick is just to keep it in binary mode.

Oh, I didn’t know there was a bytearray data type in Python. Good to know!!

Awesome R.White!! I’ll try your solution too. Thanks!!