1

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.

2
  • Just to check if I understand it correctly: Base is derived from QGraphicsItem ?! Commented Jan 13, 2016 at 8:54
  • Yes, that's correct! Commented Jan 13, 2016 at 10:40

1 Answer 1

3

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 :-)

Sign up to request clarification or add additional context in comments.

8 Comments

So what is the difference between using qgraphicsitem_cast and dynamic_cast?
I think qgraphicsitem_cast use dynamic_cast under the hood, but I haven't checked it. Basically it's safer since qgraphicsitem_cast checks whether function type() returned id that equals DerivedQGraphicsItem::Type before casting.
@LebenAsa: If it used dynamic_cast, there wouldn't have been a need for type(). Qt predates decent C++ compilers and assumed RTTI was broken.
I thought qgraphicsitem_cast has bad design, or rather just don't have it at all. The only way it would be useful is that you can select items with this type, but it is not used anywhere, only for cast. Providing constexpr Type may sometimes be impossible, like if you have plugins, but I do not see why It cannot be declarated as static int, witch makes qgraphicsitem_cast not so completely useless, but you still need some kind of registry automation. dynamic_cast here is a good choice.
@MSalters @Arpegius: Yes. The problem with QGraphicsItem is the lack of signals and slots, thus encourages people to do manual search and cast. type() and qgraphicsitem_cast helped this somewhat, but its nowhere elegant.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.