In my application is written in Qt, I have a QGraphicsScene. In this QgraphicsScene there is an Image and some items that draw by user. I want to save this QgraphicsScene with whole of stuff on it.

for example I have this stuff:

QGraphicsPixmapItem* image;
QPointF point;
ChromosomeShape::type pointType;
QGraphicsItem *item;

when i save these to file, it seems there is no problem

but when I want to load (datastream >> image;), I got some error about "no match 'operator >>', qdatastream and QGraphicsPixmapItem*"

but I don't want to overload operaptor>> for QGraphicsPixmapItem, and really I don't know how.

Q: is there any way I can do this?

any idea is well appreciated.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top