1

In the Qt documentation of QDataStream it says

The QDataStream class provides serialization of binary data to a QIODevice.

so that's what I want to do. I want to send bytes in PySide on Python 3.X to a QDataStream.

writeRawData however expects unicode as input.

import zlib
from PySide import QtCore

file = QtCore.QFile("test.dat")
file.open(QtCore.QIODevice.WriteOnly)

data = "some text"
compressed_data = zlib.compress(data.encode()) # type is now bytes

out = QtCore.QDataStream(file)
out.writeRawData(compressed_data)

gives a TypeError:

TypeError: 'PySide.QtCore.QDataStream.writeRawData' called with wrong argument types:
  PySide.QtCore.QDataStream.writeRawData(bytes)
Supported signatures:
  PySide.QtCore.QDataStream.writeRawData(unicode, int)

Furthermore writeBytes from QDataStream is not implemented by PySide (1.2.2).

So, how can I send binary data over a QDataStream in PySide and Python 3.X?


Background: In the end I want to send binary data to a QSocket conveniently via a QDataStream and I want to compress it before using zlib .

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104

1 Answers1

2

I can answer my own question. The solution is to wrap the byte string in a QByteArray and use the shift left/right operators of QDataStream.

Example for writing:

# wrap data (type byte) in QByteArray
bytearray = QtCore.QByteArray(data)

# write to data stream
qdatastream << bytearray

Example for reading:

# allocate empty qbytearray
bytearray = QtCore.QByteArray()

# read from data stream
qdatastream >> bytearray
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104