Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
[Solved] QGraphicsView: Item added via addItem not displaying in QGraphicsView
kaluga last edited by
(Apologies if this should be in a Newbie Forum, this seemed to be the closest match)
I'm sure this is something silly I'm doing, but, when I try to add a QGraphicsRectItem (in this example) using QGraphicsScene::addItem, it won't display in a QGraphicsView.
for example: This does not display anything in the QGraphicsView(ui->mainView)
qDebug() << "fooQGRectItem rect " << fooQGRectItem.rect() << " at " << fooQGRectItem.pos() << "using " << fooQGRectItem.pen() << " in " << fooQGRectItem.scene();
however this does;
QGraphicsRectItem *fooQGRectItemPtr = mainScene.addRect(QRect(0,0,600,300), QPen(Qt::red,4), QBrush(Qt::yellow));
qDebug() << "fooQGRectItemPtr rect " << fooQGRectItemPtr->rect() << " at " << fooQGRectItemPtr->pos() << "using " << fooQGRectItemPtr->pen() << " in " << fooQGRectItemPtr->scene();
Obviously the second, working, method is a lot less code, however this example is just to show the problem in the simplest form. My actual problem is getting an Object derived from QGraphicsRectItem to display.
The only reasons I can think that it wouldn't display are:
Pen and Brush colour are same as background, and pen width is 0
Is hidden behind other objects
Visible is not set
Has not been updated
Is out of the View
Is not actually in the scene
However the two debug lines seem to indicate that everything is working correctly. Also using QGraphicsView::centerOn also verifies that the object is in the scene, just not visible.
An help very much appreciated in advance.
steno last edited by
QGraphicsRectItem is created on the stack and goes out of scope when you leave that function. You have to create the rect on the heap.
QGraphicsRectItem * fooQGRectItem = new QGraphicsItemRect(QRect(0,0,300,600));
ZapB last edited by
Yup as steno said it is a scoping issue. It is more usual to create such objects on the heap with new as opposed to on the stack. As long as you provide your items a suitable parent the parent will take care of cleaning up the children when the parent it destroyed.
kaluga last edited by
Thank you very much for your answers guys.
I had briefly thought of scope but thought I would have gotten an error when the Scene realised that it couldn't see an object it was supposed to have owned.. and of course all my debugging was in the same scope (duh :) )
For anyone else starting out like me and reading this, this link was quite useful in explaining the scope of the stack and heap.
Thanks also for the tip about using the parent to clean up too, ZapB.