我有三个类:
Base
、Derived1
和Derived2
,其中Base
继承自QGraphicsItem
,另外两个类继承自Base
。我正在尝试通过覆盖 Qt documentation中提到的
qgraphicsitem_cast
方法来使用 type()
投射它们。但是,它不适用于 Base
类并返回 NULL
,而它适用于 Derived1
和 Derived2
类。我尝试使用标准的 C++ 方式,dynamic_cast
,它有效。我怎样才能让它也适用于Base
班级?
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();
}