2013-05-17 99 views
0

我在本地目录中有一个“tooltip.png”文件。 下面的代码工作时,我把它放在INT主要(),但是当我把它放在我的主窗口类的构造函数不起作用:QGraphicsView未显示图片

QGraphicsScene scene; 
QGraphicsView *view = new QGraphicsView(&scene); 
QGraphicsPixmapItem item(QPixmap("tooltip.png")); 
scene.addItem(&item); 
view.show(); 
在INT主(

)显示它的图片,但在构造函数中没有按” t

回答

1

您在堆栈上创建了scene,这意味着一旦超出范围(即构造函数结束处的范围),它将被删除。 尝试构建scene这样你的主窗口的构造函数中:

QGraphicsScene scene(this); 

通过提供父母到现场,QT会确保它一起仍然活着与父母(在你的情况,你主窗口)。 由于Qt处理内存管理,您可以使用指针而不用担心内存泄漏:

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