PDA

View Full Version : Best way to cast QList of base class pointers to derived class pointers



wayfaerer
6th April 2012, 05:30
I have a QList of base class pointers:


QList<QGraphicsItem*> selectedItems = myGraphicsScene->selectedItems();

but I'd like it to be a derived class, e.g., QList<DerivedGraphicsItem*>. Is there any way to do this other than iterating through the list and creating a new one?

Note that in this particular case, I want to static cast, although I'm curious how it would work to dynamic cast in this situation too.

mentalmushroom
6th April 2012, 06:55
As far as I know, neither static nor dynamic cast will do that. QList<DerivedGraphicsItem*> is not a subclass of QList<GraphicsItem*>, moreover, QList is a template class, that means it could be specialized differently for different template paremeters, so it is not legal to cast. If you explain why do you need to cast it, maybe I can propose a solution.

ChrisW67
6th April 2012, 10:43
You will have to build a second list, casting each base class pointer to the derived class pointer, and discarding those that do not cast. If they are QGraphicsItem objects then you can use qgraphicsitem_cast. I would not use static_cast unless you can guarantee all the items in the scene are of the one type, and even then...

wayfaerer
6th April 2012, 16:44
My QGraphicsScene consists of only one type of selectable item (but other types of non-selectable items), so it's certain that any selected items will be of that type, so static_cast should be okay.

It's not a big deal, I'm just asking because whenever I try to operate on the selected items, I have to cast in a bunch of places, and it's a little messy.