PDA

View Full Version : Unable to get QList of custom QGraphicsItems (newbie) from scene



@vijay@
10th September 2008, 16:17
Hi,
I have created a subclass from QGraphicsItem


class Node : public QGraphicsItem{
};

and added few nodes using following code to a QGraphicsscene


for(int j=0;j<no_of_nodes;j++){
Node *node = new Node();
node->apply_color(QColor(Qt::green));
node->setPos(0,0);
node->apply_text(node_name[j]);
scene->addItem(node);
}

Now i want to access these nodes later for changing color (apply_color() function defined in Node). I looked at a function called
QList<QGraphicsItem *> scene->items();
so i tried to get the list of graphicalitems using

QList<Node *> listofitems = scene->items();
but im getting the following error

conversion from ‘QList<QGraphicsItem*>’ to non-scalar type ‘QList<Node*>’ requested

And how does the QList<QGraphicsItem *> scene->items(); return items ??? in the same order as they are added???
I have also uploaded the code

Thanx

jpn
10th September 2008, 17:49
You cannot directly convert between two template containers which contain different types.


QList<QGraphicsItem *> items = scene->items();
foreach (QGraphicsItem* item, items)
{
Node* node = dynamic_cast<QGraphicsItem*>(item);
if (node)
{
...
}
}

See also qgraphicsitem_cast for more efficient casting. It just requires support from Node class.