Qt/C++ 在不使用 dynamic_cast 的情况下将 QGraphicsItem 转换为自定义 QGraphicsItem

Qt/C++ Cast QGraphicsItem to custom QGraphicsItem without using dynamic_cast

我从 OOAD class 了解到 dynamic_cast 是一个糟糕的设计 但我不知道在 Qt 中没有 dynamic_cast 我怎么能做我想做的事 因为我不能只在 QGraphicsItem 中做多态性。 这是我的代码。

void Scene::changeName(){
    QList<QGraphicsItem*> selecitems = this->selectedItems();
    if(selectedItems().size()==1){
        Base* object = dynamic_cast<Base*>(selecitems[0]);
        bool isok;
        if(object){
            QString name = QInputDialog::getText( views().first()
                , tr("Change object name")
                , tr("Enter a name"),QLineEdit::Normal, "name", &isok);
            if(isok){
                object->setName(name);
            }
        }
    }
}

我想更改一个项目的名称,如果它是一个 Base 对象并且它是唯一被选中的对象。

而且我需要 Base class 中的函数 "setName"。 有没有不用 dynamic_cast 就可以做我想做的事情的方法?

在正常情况下,我将在 QGraphicsItem 中渗透函数 "SetName", 但似乎我无法在 Qt 中执行此操作。

Qt 有自己的 QGraphicsItem 转换函数:qgraphicsitem_cast。来自文档:

T qgraphicsitem_cast(QGraphicsItem * item)

Returns the given item cast to type T if item is of type T; otherwise, 0 is returned.

Note: To make this function work correctly with custom items, reimplement the type() function for each custom QGraphicsItem subclass.

另一方面,糟糕的设计很糟糕,但 dynamic_cast 有多糟糕取决于你如何使用它:-)