14

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?

dhein
  • 6,431
  • 4
  • 42
  • 74
Davit Tvildiani
  • 1,915
  • 3
  • 19
  • 29

2 Answers2

25

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.

laurent
  • 88,262
  • 77
  • 290
  • 428
  • 1
    And how avoid Memory leak ? :=) I have to release memory right ¿? :) – Davit Tvildiani Aug 22 '11 at 08:59
  • 2
    Yes you will need to clean up yourself with delete. I would suggest that you declare your QGraphicsScene (and QGraphicsPixmapItem if it doesnt get copied during additem) as a class pointer variable. And I would then suggest that you use some sort of smart pointer when you declare the variable e.g. QSharedPointer: QSharedPointer ptr_scene; this->ptr_scene = QSharedPointer(new QGraphicsScene()) Then memory are managed when MainWindow is closed. – thomas Aug 18 '14 at 06:47
8

If you don't have to stick with QGraphicsView one possibility is to use QLabel instead. I didn't manage to solve it for QGraphicsView...

QString filename = "X:/my_image";
QImage image(filename);
ui->label->setPixmap(QPixmap::fromImage(image));
Cornelis
  • 123
  • 1
  • 6