gpt4 book ai didi

c++ - 使用 stackBefore 更改 QGraphicsItem 堆栈顺序

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:00 24 4
gpt4 key购买 nike

我有一个 QGraphicsItem“p”,其中有 4 个 child a、b、c 和 d,按顺序插入。

#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();
}

我想像这样将项目 a 放在 c 和 d 之间:

enter image description here

所以基本上我使用 stackBefore 并执行:

a->stackBefore(d);

但它不起作用。所以我看了一下 QGraphicsItem 的代码,似乎如果该项目之前已经堆叠(立即或不)它不会移动:

// 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) {

我可以这样做:

b->stackBefore(a);
c->stackBefore(a);

移动a下的所有元素。或者:

a->setParentItem(nullptr);
a->setParentItem(p);
a->stackBefore(d);

删除 a,然后将其重新插入到顶部,这样我就可以使用 stackBefore。

这两种解决方案看起来都不是很有效。第一个不缩放,第二个缺乏语义。

是否有一种优雅的方式来实现这一目标?

最佳答案

我会为每个图形项目分配一个明确的 Z 值:

int z = 0;
a->setBrush(Qt::blue);
a->setZValue(++z);
b->setBrush(Qt::red);
b->setZValue(++z);
c->setBrush(Qt::yellow);
c->setZValue(++z);
d->setBrush(Qt::green);
d->setZValue(++z);

然后,在使用 stackBefore() 之前,更改移动项目的 Z 值:

a->setZValue(d->zValue());
a->stackBefore(d);

关于c++ - 使用 stackBefore 更改 QGraphicsItem 堆栈顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com