amin
amin

Reputation: 28

How can I write data of a QVector that consists of objects of my class to file?

How can I write data of a QVector that consists of objects of my class to file? how can I do that?

Upvotes: 0

Views: 1228

Answers (1)

Tyler Jandreau
Tyler Jandreau

Reputation: 4335

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!

Upvotes: 2

Related Questions