简体   繁体   中英

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. 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. Is there anyway to do what I want without using 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.

Qt has its own casting function for QGraphicsItem : qgraphicsitem_cast . From the documentation:

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.

On another note, bad design is bad, but how bad dynamic_cast is depends on how you use it :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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