I have three classes: Base, Derived1, and Derived2, where Base inherits from QGraphicsItem, and the other two classes inherit from Base. I am trying to cast them using qgraphicsitem_cast by overriding the type() method as mentioned in the Qt documentation. However, it does not work for Base class and returns NULL, whereas it works for Derived1 and Derived2 classes. I tried using the standard C++ way, dynamic_cast, and it works. How can I make it work for the Base class as well?
class Base : public QGraphicsItem {
public:
Base(){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {}
[[nodiscard]] QRectF boundingRect() const override {}
enum {Type = QGraphicsItem::UserType + 1};
[[nodiscard]] int type() const override { return Type; }
};
class Derived1 : public Base {
public:
Derived1(){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {}
[[nodiscard]] QRectF boundingRect() const override {}
enum {Type = QGraphicsItem::UserType + 2};
[[nodiscard]] int type() const override { return Type; }
};
class Derived2 : public Base {
public:
Derived2(){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override {}
[[nodiscard]] QRectF boundingRect() const override {}
enum {Type = QGraphicsItem::UserType + 3};
[[nodiscard]] int type() const override { return Type; }
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
auto d1 = new Derived1;
scene.addItem(d1);
auto item = scene.items().first();
auto castedItem1 = qgraphicsitem_cast<Base*>(item); // this line return NULL (Why?)
auto castedItem2 = qgraphicsitem_cast<Derived1*>(item); // Work
auto castedItem3 = dynamic_cast<Base*>(item); // Work!
return QApplication::exec();
}