如何使用qgraphicsitem_cast将继承自QGraphicsItem的Base类的对象强制转换为其派生类?

问题描述 投票:0回答:0

我有三个类:

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();
}
c++ qt casting qgraphicsitem
© www.soinside.com 2019 - 2024. All rights reserved.