Qt Graphics View, show image !, Widget

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 an image from a file, the code works fine, but the images disappear very quickly.

How to pause image display?

And how to load an image into the "graphicsView" widget?

My code is:

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

This does not work.

How to fix it?

+6
source share
2 answers

You need to create all your objects on the heap, otherwise they will be 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 may be related - scene is assigned ui->graphicsView , but it is deleted immediately after that, so create all your objects on the heap again.

+16
source

If you do not need to stick to QGraphicsView, then it is possible to use QLabel. I could not solve it for QGraphicsView ...

 QString filename = "X:/my_image"; QImage image(filename); ui->label->setPixmap(QPixmap::fromImage(image)); 
+6
source

Source: https://habr.com/ru/post/895527/


All Articles