I have a QGraphicsItem "p" with 4 children a, b, c and d, inserted in that order.
#include <QtWidgets/QApplication>
#include <QtWidgets/QGraphicsScene>
#include <QtWidgets/QGraphicsItem>
#include <QtWidgets/QGraphicsView>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QGraphicsScene scene(0, 0, 200, 200);
QGraphicsView view(&scene);
QGraphicsItem* p = new QGraphicsRectItem(nullptr);
scene.addItem(p);
QGraphicsRectItem* a = new QGraphicsRectItem( 0, 0, 40, 40, p);
QGraphicsRectItem* b = new QGraphicsRectItem(10, 10, 40, 40, p);
QGraphicsRectItem* c = new QGraphicsRectItem(20, 20, 40, 40, p);
QGraphicsRectItem* d = new QGraphicsRectItem(30, 30, 40, 40, p);
// cosmetic
p->moveBy(40, 40);
a->setBrush(Qt::blue);
b->setBrush(Qt::red);
c->setBrush(Qt::yellow);
d->setBrush(Qt::green);
view.show();
return app.exec();
}
I want to put item a between c and d like this:
So basically I use stackBefore and do:
a->stackBefore(d);
But it doesn't work. So I took a look at QGraphicsItem's code and it seems like if the item is already stacked before (immediately or not) it will not move:
// Only move items with the same Z value, and that need moving.
int siblingIndex = sibling->d_ptr->siblingIndex;
int myIndex = d_ptr->siblingIndex;
if (myIndex >= siblingIndex) {
I can either do:
b->stackBefore(a);
c->stackBefore(a);
which move all elements under a. or:
a->setParentItem(nullptr);
a->setParentItem(p);
a->stackBefore(d);
which remove a, and re-insert it on top so I can use stackBefore.
Both solutions look no very efficient. The first one, does not scale and the second one lack semantics.
Is there an elegant way to achieve this ?