A simple local approach is to find a Z value by checking all colliding items. If you use Qt::IntersectsItemBoundingRect, this operations is very fast.
// Find largest Z
qreal maxZ = 0;
foreach
(QGraphicsItem *item, clickedItem
->collidingItems
(Qt
::IntersectsItemBoundingRect)) maxZ = qMax(maxZ, item->zValue());
// Assign new Z
clickedItem->setZValue(maxZ + some);
// Find largest Z
qreal maxZ = 0;
foreach (QGraphicsItem *item, clickedItem->collidingItems(Qt::IntersectsItemBoundingRect))
maxZ = qMax(maxZ, item->zValue());
// Assign new Z
clickedItem->setZValue(maxZ + some);
To copy to clipboard, switch view to plain text mode
If you nest items (child items etc), you'll have to compare against top level items' Z values:
// Find largest Z
qreal maxZ = 0;
foreach
(QGraphicsItem *item, clickedItem
->collidingItems
(Qt
::IntersectsItemBoundingRect)) maxZ = qMax(maxZ, item->topLevelItem()->zValue());
// Assign new Z
clickedItem->topLevelItem()->setZValue(maxZ + some);
// Find largest Z
qreal maxZ = 0;
foreach (QGraphicsItem *item, clickedItem->collidingItems(Qt::IntersectsItemBoundingRect))
maxZ = qMax(maxZ, item->topLevelItem()->zValue());
// Assign new Z
clickedItem->topLevelItem()->setZValue(maxZ + some);
To copy to clipboard, switch view to plain text mode
Another approach is to normalize the Z values of all colliding items, for example like this:
int z = 0;
foreach
(QGraphicsItem *item, clickedItem
->collidingItems
(Qt
::IntersectsItemBoundingRect)) item->topLevelItem()->setZValue(--z);
clickedItem->topLevelItem()->setZValue(0);
int z = 0;
foreach (QGraphicsItem *item, clickedItem->collidingItems(Qt::IntersectsItemBoundingRect))
item->topLevelItem()->setZValue(--z);
clickedItem->topLevelItem()->setZValue(0);
To copy to clipboard, switch view to plain text mode
Hope that helps. :-)
Bookmarks