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?
I agree with the other posters, the QGraphicsItem could really be viewed as a view item and so separating your model data into its own class would probably be better.
That said, I think your crash is caused by an inappropriate cast.
If you do the following:
You should see that r == qi, r == qr, but r != i. If you think about how an object that multiply inherits is represented in memory, the first base class is first in memory, the second base class is second, and so forth. So the pointer to the second base class will be offset by [approximately] the sizeof the first base class.
So to fix your code, I think you need to do something like:
This is one of many reasons, I like to avoid multiple inheritance whenever possible. I strongly recommend separating you model data, as previously recommended.