简体   繁体   English

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

[英]Qt/C++ Cast QGraphicsItem to custom QGraphicsItem without using dynamic_cast

I learned from OOAD class that dynamic_cast is a bad design but I don't know how can I do what I want without dynamic_cast in Qt cause I can't just do polymorphism in QGraphicsItem. 我从OOAD类中学到,dynamic_cast是一个糟糕的设计,但是我不知道在Qt中没有dynamic_cast怎么办我想做的事情,因为我不能只在QGraphicsItem中做多态。 Here is my code. 这是我的代码。

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);
            }
        }
    }
}

I want to change an item's name if it is a Base object and its the only one selected. 我想更改一个项目的名称,如果它是一个基础对象,并且它是唯一选中的一个。

And I need the function "setName" in Base class. 我需要基类中的函数“ setName”。 Is there anyway to do what I want without using dynamic_cast? 无论如何,不​​使用dynamic_cast就可以做我想做的事吗?

In normal condition , I'll percolate up the function "SetName" in QGraphicsItem, but it seems that I can't do this in Qt. 在正常情况下,我将在QGraphicsItem中渗透函数“ SetName”,但似乎无法在Qt中做到这一点。

Qt has its own casting function for QGraphicsItem : qgraphicsitem_cast . Qt对于QGraphicsItem具有自己的转换功能: qgraphicsitem_cast From the documentation: 从文档中:

T qgraphicsitem_cast(QGraphicsItem * item) T qgraphicsitem_cast(QGraphicsItem *项目)

Returns the given item cast to type T if item is of type T; 如果项目为T类型,则返回给定的类型转换为T的项目; otherwise, 0 is returned. 否则,返回0。

Note: To make this function work correctly with custom items, reimplement the type() function for each custom QGraphicsItem subclass. 注意:要使此函数与自定义项一起正常工作,请为每个自定义QGraphicsItem子类重新实现type()函数。

On another note, bad design is bad, but how bad dynamic_cast is depends on how you use it :-) 另一个需要注意的是,糟糕的设计很糟糕,但是dynamic_cast糟糕程度取决于您使用它的方式:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM