Answer the question
In order to leave comments, you need to log in
Qt. How to serialize objects containing collections?
In general, there are the following classes:
class Institution //Класс "учебное заведение"
{
...
private:
...
QList<Pupil *> Pupils; //Коллекция учеников
};
class Pupil //Класс "ученик"
{
...
private:
...
QList<Exam *> Lessons; //Коллекция предметов
};
class Exam //Класс "экзамен"
{
...
};
QList<Institution *> institutions;
...
Institution bf("", 0);
char str[1024];
strcpy(str, filename.toStdString().c_str());
std::ofstream out(str, std::ios::out | std::ios::binary);
for (int i = 0; i < institutions.size(); i++)
{
bf = *institutions[i];
int a = sizeof bf;
out.write((char *) &bf, sizeof bf);
}
out.close();
QList<Institution *> institutions;
...
institutions.clear();
char str[1024];
strcpy(str, filename.toStdString().c_str());
std::ifstream in(str, std::ios::in | std::ios::binary);
while (!in.eof() && in.peek() != EOF)
{
Institution *bf = new Institution("", 0);
int a = sizeof bf;
in.read((char *) bf, sizeof *bf); //!
institutions.append(bf);
}
in.close();
/*Коллекция*/
ArrayList list = new ArrayList();
/*Запись*/
try
{
FileOutputStream fos = new FileOutputStream(file.toString());
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
fos.close();
}
catch(IOException ioe)
{
}
/*Считывание*/
FileInputStream fis = new FileInputStream(file.toString());
ObjectInputStream ois = new ObjectInputStream(fis);
try
{
list = (ArrayList) ois.readObject();
}
catch (ClassNotFoundException e)
{
}
ois.close();
fis.close();
Answer the question
In order to leave comments, you need to log in
Qt has a special QDataStream class for serialization. The classes that you want to serialize need to implement two operators (for reading and for writing):
QDataStream &operator<< (QDataStream &out, const T &obj);
QDataStream &operator>> (QDataStream &in, T &obj);
QFile f("path");
if (f.open(QIODevice::ReadOnly) { // or WriteOnly, or ReadWrite
QDataStream s(&f);
T obj;
s >> obj; // for write s << obj
}
QList<Institution> lst
, then you can just write s << lst
for serialization, and if the pointer, then no, it is possible to write the appropriate operator for the pointer - this is the solution. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question