How can I write data of a QVector that consists of objects of my class to file? how can I do that?
Asked
Active
Viewed 1,198 times
0
-
you need to serialize your class. See here for example, [serialization-with-qt](http://stackoverflow.com/questions/2570679/serialization-with-qt) [Qt5_QFile_Serialization_Class](http://www.bogotobogo.com/Qt/Qt5_QFile_Serialization_Class.php), but there are many other posts. I found it easier to serialize to [JSON](http://doc.qt.io/qt-5/json.html) – Miki Jul 09 '15 at 18:51
1 Answers
2
Your question is quite general but I will do my best.
Assume that you've written a class that you would like to store in a QVector
. This is simple enough:
class MyClass {
public:
MyClass(double input) : a(input) {}
private:
double a;
};
QVector<MyClass> classes;
classes.push_back(MyClass(1.0));
classes.push_back(MyClass(2.0));
classes.push_back(MyClass(3.0));
You want to serialize the class MyClass
so the operator<<
understands how to write it to an output stream. You can do this by adding the following function signatures to the MyClass
definition:
class MyClass {
// omitted
friend QDataStream& operator<<(QDataStream &stream, const MyClass &class) {
stream << class.a;
return stream;
}
};
While I defined the operator<<
in the class itself, you should define it in your implementation file.
Now, we are free to write the output of the vector to the file:
QString filename = "/path/to/output/file/myclass.txt";
QFile fileout(filename);
if (fileout.open(QFile::ReadWrite | QFile::Text)) {
QTextStream stream(&fileout);
for (QVector<MyClass>::const_iterator it = classes.begin();
it != classes.end(); ++it) {
out << *it;
}
// and close the file when you're done with it
fileout.close();
}
That should be enough to get you started. Keep in mind that I have not tested this code so use at your own risk!

Tyler Jandreau
- 4,245
- 1
- 22
- 47