Qt Graphics View , show image ! , Widget
Asked Answered
P

2

15

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?

Phocis answered 21/8, 2011 at 12:0 Comment(0)
D
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.

Disproportion answered 21/8, 2011 at 12:6 Comment(2)
And how avoid Memory leak ? :=) I have to release memory right ¿? :)Phocis
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: <in class header> QSharedPointer<QGraphicsScene> ptr_scene; <in source file> this->ptr_scene = QSharedPointer<QGraphicsScene>(new QGraphicsScene()) Then memory are managed when MainWindow is closed.Jeconiah
P
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));
Petroglyph answered 27/6, 2012 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.