【发布时间】:2020-01-13 01:25:24
【问题描述】:
我有一个 QGraphicsItem “p”,其中有 4 个孩子 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 之间,如下所示:
所以基本上我使用 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。
这两种解决方案看起来都不是很有效。第一个无法扩展,第二个缺乏语义。
有没有优雅的方法来实现这一点?
【问题讨论】:
-
感谢您的提问,这解释了为什么我的
stackBefore()呼叫不起作用,我从未正确调查过(改为使用 Z 顺序)。 :-) 看起来我们真的需要一个sortBefore()函数来处理这个问题。令人失望的是,API 中没有任何内容,因为很多信息已经在私有部分中,并且更容易在内部处理。
标签: c++ qt qt5 qgraphicsscene qgraphicsitem