Read and write a QGraphicsScene from and to a binary file is not provided by Qt, and will be extremely long and difficult to do by yourself if you are not used to serialization with abstract classes and tree hierarchies.This will be your best friend if you want to give it a try. In the case of QGraphicsScene, you are in this situation
In your case, you probably only want to read/write a small subset of QGraphicsScene that you know in advance, so may be feasible though. For instance, just start as you did by trying to read/write a QGraphicsPixmapItem
. Hence, you do have to implement yourself the two methods:
QDataStream &operator<<(QDataStream &, const QGraphicsPixmapItem &);
QDataStream &operator>>(QDataStream &, QGraphicsPixmapItem &);
That don't exist yet. What you've probably written when you said "when I save these to file, it seems there is no problem" is only the address of your QGraphicsPixmapItem, i.e just a 32 or 64bit number, which is useless to be able to read it again ;-) More specifically, you probably did:
datastream << image; // writing a QGraphicsPixmapItem*, useless
instead of:
datastream << *image; // writing a QGraphicsPixmapItem, useful but not provided by Qt
Hopefully, this should not be too complicated to write, since Qt already provides the QPixmap and QTransform serialization functions. Try something like:
QDataStream &operator<<(QDataStream & out, const QGraphicsPixmapItem & item)
{
out << item.transform() << item.pixmap();
return out;
}
QDataStream &operator>>(QDataStream & in, QGraphicsPixmapItem & item)
{
QTransform t;
QPixmap p;
in >> t >> p;
item.setTransform(t);
item.setPixmap(p);
return in;
}
And then you can save you QGraphicsPixmapItem *
with:
datastream << *image;
And load it with:
QGraphicsPixmapItem * image = new QGraphicsPixmapItem();
datastream >> *image;
If you need to save other properties of your QGraphicsPixmapItem
(such as isActive
, isVisible
, acceptDrop
, offset
, shapeMode
, transformationMode
, etc...), just proceed the same way.