PyQt6: Get QGraphicsItem in a group which is at a specific position

88 Views Asked by At

The QGraphicsScene class has a method .itemAt which returns the top-most item on the scene at specified coordinates (x, y). However, what if you don't want to get the top-most item? I would like to delete an item at coordinates (x, y) which is contained in a specific QGraphicsItemGroup when the mouse is dragged while the left mouse button is held. The QGraphicsItemGroup has a method .contains which can detect if any item in the group is at (x, y), but doesn't actually return an object at this point.

I tried using the .setZValue method to temporarily move the item group to the top level using the following function which executes when the mouse is moved while the left mouse button is held:

if itemGroup contains(QPointF(x, y)):
    itemGroup.setZValue(100)
    oldItem = scene.itemAt(x, y, QTransform())
    itemGroup.removeItem(oldItem)
    scene.removeItem(oldItem)
    itemGroup.setZValue(oldZvalue)

Here itemGroup is the QGraphicsItemGroup, scene is the QGraphicsScene, and oldZvalue is the Z-value of the item group prior to changing it for the purposes of deletion. This unfortunately deletes things outside the item group.

Of course, I could just iterate through all items in the group and check their positions, but I would hope there is a better way.

0

There are 0 best solutions below