PDA

View Full Version : Saving/Loading a Qlist.



harvey_slash
2nd October 2013, 12:22
I have a Qlist 'list' , and list is the instance of my data type TEST

class test
{



public:
int a;
void lol(int t)
{
a=t;

}
};

I want to save this qlist to a file. (say "save.bak")
Later, when I open it, I want to be able to open it as a QList (name->'lista'), and add, modify etc.
I will copy lista to list, and overwrite list to "save.bak"

I am new to it. I couldn't understand how to serialize & deserialize (checked a bit online)
so, please give an example as to how to do it.
thanks.

anda_skoa
2nd October 2013, 13:39
Serialization always depends on the format you want to serialize to, e.g. serializing to XML or JSON, some CSV-like format or an INI-style format.

What are your requirements? Do you need to be able to read the data from an earlier version of the program, do you need to be able to read the data from a future version of the program, does the format have to be human-readable, etc?

Cheers,
_

harvey_slash
2nd October 2013, 14:13
I don't want to do any of that.
doesn't even have to be human readable.
I don't need compatibility too.(for now)
this is a simple project for my school.

anda_skoa
2nd October 2013, 17:11
Then the easiest way is to use QDataStream.

Cheers,
_

Radek
2nd October 2013, 17:14
The simplest way is using existing tools. QList has I/O operators for QDataStream. You need to equip your test class by the corresponding I/O operators:



friend QDataStream& operator << ( QDataStream& out, const test& ob )
{
output ob to out;
return out;
}

friend QDataStream& operator >> ( QDataStream& in, test& ob )
{
read data from in and and initialize ob;
return in;
}


Now, open a file (QFile), associate it with a QDataStream (say, fileio) and do fileio << list; or fileio >> list. The QList class will iterate through its contents and outputs stored items to the file. Or, it will append items stored in the file to the current contents of the list. Therefore, before reading in, do list.clear(). The output is a binary file.