Serializing QGraphicsScene contents
Posted
by Rob
on Stack Overflow
See other posts from Stack Overflow
or by Rob
Published on 2010-06-08T18:01:35Z
Indexed on
2010/06/08
18:42 UTC
Read the original article
Hit count: 303
I am using the Qt QGraphicsScene
class, adding pre-defined items such as QGraphicsRectItem
, QGraphicsLineItem
, etc. and I want to serialize the scene contents to disk. However, the base QGraphicsItem
class (that the other items I use derive from) doesn't support serialization so I need to roll my own code. The problem is that all access to these objects is via a base QGraphicsItem
pointer, so the serialization code I have is horrible:
QGraphicsScene* scene = new QGraphicsScene;
scene->addRect(QRectF(0, 0, 100, 100));
scene->addLine(QLineF(0, 0, 100, 100));
...
QList<QGraphicsItem*> list = scene->items();
foreach (QGraphicsItem* item, items)
{
if (item->type() == QGraphicsRectItem::Type)
{
QGraphicsRectItem* rect = qgraphicsitem_cast<QGraphicsRectItem*>(item);
// Access QGraphicsRectItem members here
}
else if (item->type() == QGraphicsLineItem::Type)
{
QGraphicsLineItem* line = qgraphicsitem_cast<QGraphicsLineItem*>(item);
// Access QGraphicsLineItem members here
}
...
}
This is not good code IMHO. So, instead I could create an ABC class like this:
class Item
{
public:
virtual void serialize(QDataStream& strm, int version) = 0;
};
class Rect : public QGraphicsRectItem, public Item
{
public:
void serialize(QDataStream& strm, int version)
{
// Serialize this object
}
...
};
I can then add Rect objects using QGraphicsScene::addItem(new Rect(,,,));
But this doesn't really help me as the following will crash:
QList<QGraphicsItem*> list = scene->items();
foreach (QGraphicsItem* item, items)
{
Item* myitem = reinterpret_class<Item*>(item);
myitem->serialize(...) // FAIL
}
Any way I can make this work?
© Stack Overflow or respective owner