Z-order of items

Have you wondered what happens when multiple items are painted in the same area of the scene? Let's try to do this:

QGraphicsEllipseItem *item1 = scene.addEllipse(0, 0, 100, 50);
item1->setBrush(Qt::red);
QGraphicsEllipseItem *item2 = scene.addEllipse(50, 0, 100, 50);
item2->setBrush(Qt::green);
QGraphicsEllipseItem *item3 = scene.addEllipse(0, 25, 100, 50);
item3->setBrush(Qt::blue);
QGraphicsEllipseItem *item4 = scene.addEllipse(50, 25, 100, 50);
item4->setBrush(Qt::gray);

By default, items are painted in the order they were added, so the last item will be displayed in front of the others:

However, you can change the z-order by calling the setZValue() function:

item2->setZValue(1);

The second item is now displayed in front of the others:

Items with a higher z value are displayed on top of the items with lower z values. The default z value is 0. Negative values are also possible. If items have the same z value, the order of insertion decides the placement, and items added later overlap those added earlier.

Ability to change the z-order of items is very important when developing 2D games. Any scene typically consists of a number of layers that must be painted in a specific order. You can set a z value for each item based on the layer this item belongs to.

The parent–child relationship between items also has an impact on the z-order. Children are displayed on top of their parent. Additionally, if an item is displayed in front of another item, the children of the former are also displayed in front of the children of the latter.