我正在尝试使用QDataStream对象加载和存储自定义QMetaType。这是一个例子:
# necessary includes...
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
raw_data = np.loadtxt('data.txt', delimiter=';', dtype=np.string_)
angle = raw_data[0 , 1:].astype(float)
distance = raw_data[1:, 0 ].astype(float)
data = raw_data[1:, 1:].astype(float)
# make the example data a bit more interesting...
data = (50 + angle[np.newaxis,:]) / (10 + np.sqrt(distance[:,np.newaxis]))
# setting up the plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# the trickey part creating the data that plot_wireframe wants
Z = data
X, Y = np.meshgrid(angle, distance)
ax.plot_wireframe(X, Y, Z)
# fancing it up a bit
ax.set_xticks(angle)
ax.set_yticks(distance[::2])
ax.set_xlabel('angle')
ax.set_ylabel('distance')
# and showing the plot ...
plt.show()
幻数回来了,但有一条消息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();
}
,然后是QVariant::save: unable to save type 'Basic' (type id: 1026).
然后是QVariant::load: unable to load type 1026.
。 Basic类只来自QMetaType文档:
14 = 14 = 0
我的想法已经用完了,有谁知道造成这个问题的原因是什么? Qt的版本是5.10.1。
答案 0 :(得分:0)
因为编译器无法读懂您的想法,您需要描述序列化的可能性,例如:
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);
在main()
中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 .
P.S。请注意,如果您在没有窗口的情况下离开return a.exec();
,则会让程序永远停留在内存中,直到您停止它为止。