-1

I have a QtDataStream:

from PyQt5 import QtCore

infile = QtCore.QFile(path)
if not infile.open(QtCore.QIODevice.ReadOnly):
   raise IOError(infile.errorString()
stream = QtCore.QDataStream(infile)

And I need to read a QVector. I need something like this:

var = QtCore.Qvector()
stream >> var

But it seems that QVector class does not exist in PyQt5. Any ideas?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Juan
  • 339
  • 3
  • 15

1 Answers1

2

PyQt cannot wrap QVector, because it is a template class. Such classes are part of the C++ language, and have no equivalent in Python. To work around this limitation, PyQt has added some special wrapper methods to the QDataStream class which provide the same functionality in a different way.

These methods are only mentioned in the PyQt documentation - so this is one of those rare cases where you must consult the PyQt docs rather than the Qt ones. The special wrapper methods are all named using the format read/write[TypeName], and include readQVariantList and writeQVariantList for reading and writing lists from a datastream:

>>> from PyQt5 import QtCore
>>> f = QtCore.QFile('test.dat')
>>> f.open(QtCore.QIODevice.ReadWrite)
True
>>> stream = QtCore.QDataStream(f)
>>> x = [3.142, 'foo', 7, QtCore.QPoint(3, 5), QtCore.QDate.currentDate()]
>>> stream.writeQVariantList(x)
>>> f.seek(0)
True
>>> stream.readQVariantList()
[3.142, 'foo', 7, PyQt5.QtCore.QPoint(3, 5), PyQt5.QtCore.QDate(2023, 4, 6)]

In addition to this, there is an alternative, lower level way to read data from template classes like QVector and QList, which involves reading the length of the container first and then reading each element one-by-one (see this answer for more details). But this will still only result in a Python list - there's no way to create an instance of QVector or QList in PyQt (and there's never any need to do so).

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Yes ekhmuro. But as you said PyQt has wrappres. But I don not find the wrapper for QVector – Juan Apr 14 '23 at 06:57
  • @Juan You do not need QVector at all. You ***must*** use the methods shown in my answer. There is no other possible solution. PyQt provides those methods because it cannot wrap QVector (which is a template class, and therefore only available in C++). – ekhumoro Apr 14 '23 at 11:26
  • @juan I have updated my answer with more details showing how things work in PyQt. – ekhumoro Apr 14 '23 at 12:07