Qt Graphics View , show image ! , Widget

Davit Tvildiani picture Davit Tvildiani · Aug 21, 2011 · Viewed 55.6k times · Source

Here is my code :

void MainWindow::on_actionOpen_Image_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,"Open Image File",QDir::currentPath());

    if(!fileName.isEmpty())
    {
        QImage image(fileName);

        if(image.isNull())
        {
            QMessageBox::information(this,"Image Viewer","Error Displaying image");
            return;
        }

        QGraphicsScene scene;
        QGraphicsView view(&scene);
        QGraphicsPixmapItem item(QPixmap::fromImage(image));
        scene.addItem(&item);
        view.show();   
    }

}

I want to display image from file, code works fine but image disappiars very fast.

How can I pause image screen?

And how can I load image in "graphicsView" widget?

My code:

void MainWindow::on_actionOpen_Image_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,"Open Image File",QDir::currentPath());

    if(!fileName.isEmpty())
    {
        QImage image(fileName);

        if(image.isNull())
        {
            QMessageBox::information(this,"Image Viewer","Error Displaying image");
            return;
        }

        QGraphicsScene scene;
        QGraphicsPixmapItem item(QPixmap::fromImage(image));
        scene.addItem(&item);

        ui->graphicsView->setScene(&scene);
        ui->graphicsView->show();    
    }
}

It does not work.

How to fix this?

Answer

laurent picture laurent · Aug 21, 2011

You need to create all your objects on the heap, otherwise they get deleted when they go out of scope:

QGraphicsScene* scene = new QGraphicsScene();
QGraphicsView* view = new QGraphicsView(scene);
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(item);
view->show();

Your second question might be related - scene is assigned to ui->graphicsView but it gets deleted immediately after, so again create all your objects on the heap.