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.
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.
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.