简体   繁体   中英

How to add children to QGraphicsItem

I have the following code, where I'm trying to have two rectangles, and then inside each, display "sub" rectangles (this is the code for one parent and one child)

auto graphicsView = std::make_unique<QGraphicsView>();
auto scene = std::make_unique<QGraphicsScene>();
graphicsView->setScene(scene.get());

auto parent1 = std::make_unique<QGraphicsRectItem>(0, 0, 100, 200);
parent1->setBrush(QBrush(QColor(Qt::cyan)));

scene->addItem(parent);

auto subRect1 = std::make_unique<QGraphicsRectItem>(10, 10, 50, 50, parent1);
subRect1->setBrush(QBrush(QColor(Qt::yellow)));

And I was excepting that when I display my QGraphicsView , I would see a cyan rectangle ( parent1 ), on top of which I would also see a yellow smaller rectangle ( subRect1 ), but I'm only able to see the cyan one.

Looking at Qt's documentation, I see that they talk about the fact that QGraphicsItem can have children, but why am I not seeing the child here?

PS: I tried adding the child in 3 different ways, but no luck:

  1. Passing the parent to the constructor (as I've shown above)
  2. Calling setParentItem on the child and passing the parent's pointer
  3. Calling parent's childItems() and then push_back or append and passing child's pointer to it

make_unique won't work here. When you add an object to the parent in Qt, you've passed off ownership. The trouble is that you also have an unique_ptr which owns it. As soon as it goes out of scope, it deletes youur object. Use new instead.

auto graphicsView = new QGraphicsView();
auto scene = new QGraphicsScene();
graphicsView->setScene(scene);

auto parent1 = new QGraphicsRectItem(0, 0, 100, 200);
parent1->setBrush(QBrush(QColor(Qt::cyan)));

scene->addItem(parent);

auto subRect1 = new QGraphicsRectItem(10, 10, 50, 50, parent1);
subRect1->setBrush(QBrush(QColor(Qt::yellow)));

(This is not fully exception proof, but Qt isn't designed to use exceptions. You could make scene, for example, with make_unique and then hand it off to the graphicsView with release(), but in practice nobody ever does that with Qt.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM