Finding items by position

If you want to know which item is shown at a certain position, you can use the QGraphicsScene::itemAt() function that takes the position in the scene's coordinate system (either a QPointF or two qreal numbers) and the device transformation object (QTransform) that can be obtained using the QGraphicsView::transform() function. The function returns the topmost item at the specified position or a null pointer if no item was found. The device transformation only matters if your scene contains items that ignore transformations. If you have no such items, you can use the default-constructed QTransform value:

QGraphicsItem *foundItem = scene.itemAt(scenePos, QTransform());

If your scene contains items that ignore transformations, it may be more convenient to use the QGraphicsView::itemAt() function that automatically takes the device transform into account. Note that this function expects the position to be in the viewport's coordinate system.

If you want all items that are located at some position, say in cases where multiple items are on top of each other, or if you need to search for items in some area, use the  QGraphicsScene::items() function. It will return a list of items defined by the specified arguments. This function has a number of overloads that allow you to specify a single point, a rectangle, a polygon, or a painter path. The deviceTransform argument works in the same way as for the QGraphicsScene::itemAt() function discussed earlier. The mode argument allows you to alter how the items in the area will be determined. The following table shows the different modes:

Mode Meaning

Qt::ContainsItemBoundingRect

The item's bounding rectangle must be completely inside the selection area.

Qt::IntersectsItemBoundingRect

Similar to Qt::ContainsItemBoundingRect but also returns items whose bounding rectangles intersect with the selection area.

Qt::ContainsItemShape

The item's shape must be completely inside the selection area. The shape may describe the item's boundaries more precisely than the bounding rectangle, but this operation is more computationally intensive.

Qt::IntersectsItemShape

Similar to Qt::ContainsItemShape but also returns items whose shapes intersect with the selection area.

 

The items() function sorts items according to their stacking order. The order argument allows you to choose the order in which the results will be returned.  Qt::DescendingOrder (default) will place the topmost item at the beginning, and  Qt::AscendingOrder will result in a reversed order.

The view also provides a similar QGraphicsView::items() function that operates in viewport coordinates.