cannot get QDataStream::setVersion to work
-
Maybe my expectation is wrong but I expect that when I set the version, that that version is used.
I'm using Qt Creator 11.0.3 and cannot when I check the version after I created a new file, the version is always the default (the latest),#include <QCoreApplication> #include <QDebug> #include <QDataStream> #include <QFile> bool saveFile(QString path) { QFile file(path); if (!file.open(QIODevice::WriteOnly)) return false; QDataStream out(&file); out.setVersion(QDataStream::Qt_6_5); out << (qint32) 0xA0B0C0D0; out << (qint32) 123; qInfo() << "The version is" << out.version(); QString title = "The anser is 42"; qint64 num = 42; out << title; out << num; file.close(); return true; } bool readFile(QString path) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) return false; QDataStream in(&file); qInfo() << "Reading version " << in.version(); file.close(); return true; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString file = "test.txt"; if (saveFile(file)) { qInfo() << "Saved"; readFile(file); } return a.exec(); } Shows the following output
The version is 20
Saved
Reading version 21What am I missing?
-
@Poldi said in cannot get QDataStream::setVersion to work:
What am I missing?
Nothing - the version is not saved in the output. You have to define your version you want to use on both sides.
-
@Poldi
I'm not sure I understand either. I expected it to write a version number to the stream, which you would check at reader side. I think @Christian-Ehrlicher is saying that is not howQDataStream::setVersion()
works, it does not actually write anything into the stream, so it's an in-memory thing only, affecting what code is executed.Have you read https://doc.qt.io/qt-6/qdatastream.html#versioning? If I understand right, the example code there shows how you can/should introduce your own, arbitrary field in the stream which the reader can use to recognise the writer's version for this purpose.