Note the comment on itemChange
:
Note that the new child might not be fully constructed when this
notification is sent; calling pure virtual functions on the child can
lead to a crash.
dynamic_cast
can also fail if the object is not fully constructed. (I don't quite understand the spec on this, but there are some cases where it will, some where it will not.) If you set the parent after constructing the item, it will work:
#include <QtGui>
class MyGraphicsItem : public QGraphicsRectItem {
public:
MyGraphicsItem(QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsRectItem(0.0, 0.0, 200.0, 200.0, parent, scene) {
setBrush(QBrush(Qt::red));
}
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) {
if (change == QGraphicsItem::ItemChildAddedChange) {
QGraphicsItem* item = value.value<QGraphicsItem*>();
if (item) {
MyGraphicsItem* my_item=dynamic_cast<MyGraphicsItem*>(item);
if (my_item) {
qDebug() << "successful!";
}
}
}
return QGraphicsRectItem::itemChange(change, value);
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
QGraphicsScene scene;
MyGraphicsItem *item = new MyGraphicsItem(NULL, &scene);
// This will work.
MyGraphicsItem *item2 = new MyGraphicsItem(NULL, &scene);
item2->setParentItem(item);
// // This will not work.
// MyGraphicsItem *item2 = new MyGraphicsItem(item, &scene);
QGraphicsView view;
view.setScene(&scene);
view.show();
return app.exec();
}