Question

I want to stop labels colliding within my Scene and as a result used this code to check for a collision:-

QGraphicsTextItem  *textLabel = new QGraphicsTextItem;
....
addItem(textLabel);

//check for collision
QList<QGraphicsItem*> items = this->items(textLabel>boundingRect(),Qt::IntersectsItemBoundingRect);

I never get any items in the list, yet on screen I can see the collisions. Am I reading the documentation incorrectly?

Was it helpful?

Solution

You're checking if any items are colliding with the label's bounding rect which is in the label's local coordinates. What you should be doing is checking relative to scene coordinates.

However, note that QGraphicsItem has this function: -

QList<QGraphicsItem *> QGraphicsItem::collidingItems(Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const

Which, as the documentation describes: -

Returns a list of all items that collide with this item. The way collisions are detected is determined by applying mode to items that are compared to this item, i.e., each item's shape or bounding rectangle is checked against this item's shape. The default value for mode is Qt::IntersectsItemShape.

So you'd be better calling: -

QList<QGraphicsItem*> items = this->collidingItems();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top