[PyQt] Interfacing with binary files: QDataStream issue

Chris Pezley chris.pezley at quantumwise.com
Tue Jun 20 10:21:01 BST 2017



On 06/19/2017 09:08 PM, Christopher Probst wrote:
> Hi,
>
> I am exploring interfacing of files with QDataStream. But it does not 
> seem to work. To write to a file I do this:
>
> file = QFile("file.dat")
> color = QColor(Qt.red)
>
> if file.open(QIODevice.WriteOnly):
>     out =  QDataStream(file)
>     out << color
>     file.flush()
>     file.close()
>
> It looks as if that the data gets written to the file. It is the 
> reading where there is a problem:
>
> file = QFile("file.dat")
> color = QVariant()
>
>
> if file.open(QIODevice.ReadOnly):
>     out = QDataStream(file)
>     out >> color
>     print(color)
>     print(color.value())
> The output is:
> <PyQt5.QtCore.QVariant object at 0x7f2cdd556f28>
> None
> What am I doing wrong?
> Thanks,
> Christopher
>
Is there a specific reason you're using binary files to store the 
information? It's probably a lot easier for you to use something like 
python's built-in json module to store files. 
(https://docs.python.org/3/library/json.html)

Here's an example which would work with your code:

    import json
    from PyQt5 import QtGui

    def write_(value):
         if isinstance(value, QtGui.QColor):
             return {'__type__': 'QColor', 'value': value.rgba()}
         raise TypeError('Unknown type:', type(value))

    def read_(entry):
         if '__type__' in entry and entry['__type__'] == 'QColor':
             return QtGui.QColor.fromRgba(entry['value'])
         return entry


    def main():
         colors = {
             'red': QtGui.QColor.fromRgb(1.0, 0.0, 0.0),
             'green': QtGui.QColor.fromRgb(0.0, 1.0, 0.0),
             'blue': QtGui.QColor.fromRgb(0.0, 0.0, 1.0),
         }

         with open('my_file.dat', 'w') as my_file:
             my_file.write(json.dumps(colors, default=write_))

         with open('my_file.dat', 'r') as my_file:
             colors_read = json.loads(my_file.read(), object_hook=read_)
         print(colors_read)


    if __name__ == '__main__':
         main()


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20170620/704ccf0e/attachment-0001.html>


More information about the PyQt mailing list