gpt4 book ai didi

c++ - 将自定义 QMetaType 与 QDataStream 结合使用

转载 作者:行者123 更新时间:2023-11-28 04:39:58 27 4
gpt4 key购买 nike

我正在尝试使用 QDataStream 对象加载和存储自定义 QMetaType。这是一个例子:

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString test1("/test1/");
const QString path1(QDir::homePath()+test1);
qDebug() << "path1 variable is " << path1;
QDir apphome(path1);
qDebug() << "apphome path is " << apphome.absolutePath();
if (!apphome.mkdir(path1)) { qDebug() << "mkdir returned false. directory already exists?"; }
if(!apphome.setCurrent(path1)) { qDebug() << "did not set current directory"; }
qDebug() << "apphome path is " << apphome.absolutePath();
Basic basic1;
Basic basic2;
basic1.value = 14;
QFile file1("file1name");
if (!file1.open(QIODevice::WriteOnly)) { qDebug() << "file1 not open."; }
QDataStream dataStream1(&file1);
QVariant qvar1;
qvar1.setValue(basic1);
dataStream1 << (quint32)12345;
dataStream1 << qvar1;
file1.close();
file1.open(QIODevice::ReadOnly);
QDataStream dataStream2(&file1);
quint32 magic;
QVariant qvar2;
dataStream1 >> magic;
qDebug() << "magic number is " << magic;
dataStream2 >> qvar2;
file1.close();
basic2 = qvar2.value<Basic>();
qDebug() << "14 = " << basic1.value << " = " << basic2.value << ".";

//MainWindow w;
//w.show();

return a.exec();
}

魔数(Magic Number)回来了,但是有一条消息 QVariant::save: unable to save type 'Basic' (type id: 1026). 然后当然是 QVariant::加载:无法加载类型 1026.,然后是 14 = 14 = 0。 Basic 类仅来自 QMetaType 文档:

struct Basic
{
Basic();
Basic(const Basic &basic);
~Basic();
int value;
};
Q_DECLARE_METATYPE(Basic)

// basic.cpp

#include "basic.h"

Basic::Basic() {}

Basic::Basic(const Basic &basic)
{
value = basic.value;
}

Basic::~Basic(){}

我的想法已经用完了,有人知道是什么导致了这个问题吗? Qt的版本是5.10.1。

最佳答案

因为编译器无法读懂你的想法,你需要描述序列化是如何可能的,例如

struct Basic
{
Basic();
Basic(const Basic &basic);
~Basic();
int value;

friend QDataStream & operator << (QDataStream &arch, const Basic& object)
{
arch << object.value;
return arch;
}

friend QDataStream & operator >> (QDataStream &arch, Basic& object)
{
arch >> object.value;
return arch;
}
};
Q_DECLARE_METATYPE(Basic);

在主函数中

qRegisterMetaType<Basic>("Basic");
qRegisterMetaTypeStreamOperators<Basic>("Basic");

在保存\加载操作发生之前。 Q_DECLARE_METATYPE 需要使用 QVariant 存储类型,这两个需要注册对象的“三巨头”以将其作为资源及其序列化方法进行管理。输出:

path1 variable is  "C:/Users/Yaroslav/test1/"
apphome path is "C:/Users/Yaroslav/test1"
mkdir returned false. directory already exists?
apphome path is "C:/Users/Yaroslav/test1"
magic number is 12345
14 = 14 = 14 .

附言请注意,如果您在没有窗口的情况下离开 return a.exec();,程序将永远保留在内存中,直到您停止它。

关于c++ - 将自定义 QMetaType 与 QDataStream 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50418380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com