QDataStream无法序列化数据 [英] QDataStream unable to serialize data

查看:280
本文介绍了QDataStream无法序列化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照教程此处进行操作并序列化Qt对象.这是我的代码:

I am trying to follow the tutorial here and serialize Qt objects. Here is my code:

QFile file("/Users/kaustav/Desktop/boo.dat");
if (!file.open(QIODevice::WriteOnly)) {
    qDebug() << "Cannot open file for writing: "
         << qPrintable(file.errorString()) << endl; //no error message gets printed
    return 0;
}
QDataStream out(&file);   // we will serialize the data into the file
out.setVersion(QDataStream::Qt_5_3); //adding this makes no difference
out << QString("the answer is");   // serialize a string
out << (qint32)42;

运行该程序时,可以在桌面上创建文件,但是文件大小为0 kB,为空白.自然,当我再尝试以下方法时:

When I run this program, the file gets created in my desktop all right, but its size is 0 kB, it is blank. Naturally, when I then try this:

 QFile file("/Users/kaustav/Desktop/boo.dat");
 file.open(QIODevice::ReadOnly);
 QDataStream in(&file);    // read the data serialized from the file
 in.setVersion(QDataStream::Qt_5_3);
 QString str;
 qint32 w;
 in >> str >> w;

我在str中得到一个空白字符串.我究竟做错了什么?如果有帮助,我正在使用基于Qt 5.2.1Qt Creator 3.1.1.

I get a blank string in str. What am I doing wrong? If of any help, I am using Qt Creator 3.1.1 based on Qt 5.2.1.

推荐答案

检查调用open时是否返回任何错误,并确保在完成操作后使用file.close()关闭该文件.

Check if there are any errors returned when calling open and ensure you close the file with file.close() when you're finished with it.

在使用Qt 5时,您应该真正使用 QSaveFile 而是在保存数据时.

As you're using Qt 5, you should really use QSaveFile instead, when saving the data.

这篇关于QDataStream无法序列化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆