Reputation: 761
I have a "tooltip.png" file in my local directory. the code below works when i put it in int main() but doesn't work when i put it in my MainWindow class constructor:
QGraphicsScene scene;
QGraphicsView *view = new QGraphicsView(&scene);
QGraphicsPixmapItem item(QPixmap("tooltip.png"));
scene.addItem(&item);
view.show();
in int main() it show the picture but in constructor doesn't
Upvotes: 0
Views: 1646
Reputation: 1229
You create scene
on the stack, meaning that it will be deleted once it goes out of scope, which is at the end of the constructor.
Try constructing scene
like this inside the constructor of your MainWindow:
QGraphicsScene scene(this);
By providing a parent to the scene, Qt will make sure it remains alive together with that parent (in your case you mainWindow). Since Qt takes care of the memory management, you can use pointers without fear of memory leaks:
QGraphicsScene* scene = new QGraphicsScene(this);
QGraphicsView* view = new QGraphicsView(scene, this); // Give the view a parent too to avoid memory leaks
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap("tooltip.png"), this);
scene->addItem(&item);
view->show();
Upvotes: 1