PDA

View Full Version : Casting QGraphicsItem



pherthyl
11th November 2007, 23:03
Hi everyone,

I'm working on a charting application using graphicsview. In my scene I have two groups of items, main "project" items that the user can interact with (boxes and lines), and extraneous items that are either children of the main items, or display items like headers/footers.

One of the common tasks I find myself doing is iterating through all the items in the scene and finding only the project items. For example, I have this type of code a lot:


void ProjectScene::setSelectedItemsFont(QFont newFont) {
QList<Sticky*> selectedNotes;
foreach(QGraphicsItem* selectedItem, selectedItems()) {
Sticky* item = dynamic_cast<Sticky*>(selectedItem);
if(item) {
selectedNotes.append(item);
}
}

Since items() returns every item, I need to find the ones that I'm interested in. Now I feel like dynamic_cast might not be the optimal way to do this (due to its inherent overhead). I've tried using QGraphicsItem::type() to find the correct items, but once I've identified which items I want, I still need to cast them to the right type to call the class-specific functions.

So basically I guess the question is if there is a better way to do this. Once I've identified the type of an item using type(), is it ok to use static_cast instead?

wysota
12th November 2007, 00:56
Use qgraphicsitem_cast() (http://doc.trolltech.com/latest/qgraphicsitem.html#qgraphicsitem_cast).