i create an graphic scene with the Graphics View Framework. I have a couple(7 - 10) of ellipse (placed vertical) created with:
ellipse = scene->addEllipse(x1, y1, w, h, pen, brush);
Now i want to prepare the graphic for an animation. First all ellipse are black. After 5 sec the first should be colored red, 5 sec after the 1st = green and the 2nd = red and so on.
My Idea was to get the first item and color the ellipse. But how can i get the ellipse items? Is there any function that perform like that?
You can use the items()
Method to get a sorted list off all Elements.
Then iterate the list and check if it is an ellipse item.
Items is also overloade for more special cases, see if one of them fits your needs.
Method:
QList<QGraphicsItem *> QGraphicsScene::items() const
You can find the documentation here: http://doc.qt.io/qt-4.8/qgraphicsscene.html#items
If you have performance concerns, here is an excerpt from the Qt Docs which I do 100% agree with:
One of QGraphicsScene's greatest strengths is its ability to efficiently determine the location of items. Even with millions of items on the scene, the items() functions can determine the location of an item within few milliseconds. There are several overloads to items(): one that finds items at a certain position, one that finds items inside or intersecting with a polygon or a rectangle, and more. The list of returned items is sorted by stacking order, with the topmost item being the first item in the list. For convenience, there is also an itemAt() function that returns the topmost item at a given position.
To check the type of the item you can use:
int QGraphicsItem::type() const
Excerpt from the docs:
Returns the type of an item as an int. All standard graphicsitem classes are associated with a unique value; see QGraphicsItem::Type. This type information is used by qgraphicsitem_cast() to distinguish between types.
Second approach is to use qgraphicsitem_cast()
directly.
Here is an Example that uses a custom GraphicsItem Node
:
// Sum up all forces pushing this item away
qreal xvel = 0;
qreal yvel = 0;
foreach (QGraphicsItem *item, scene()->items()) {
Node *node = qgraphicsitem_cast<Node *>(item);
if (!node)
continue;
QPointF vec = mapToItem(node, 0, 0);
qreal dx = vec.x();
qreal dy = vec.y();
double l = 2.0 * (dx * dx + dy * dy);
if (l > 0) {
xvel += (dx * 150.0) / l;
yvel += (dy * 150.0) / l;
}
}