I would like to display pictures of a person.
When “load new picture” is selected, the open file dialog will choose a new file, then the picture is to be switched to the new one.
I tried to use QGraphicsView
and QGraphicsScene
as follows.
void MainWindow::onPhotoLoadClicked()
{
QString filename = QFileDialog::getOpenFileName(this, "Open Image", "", "Image Files (*.png *.jpg *.bmp)");
QPixmap pixmap{ filename };
if (pixmap.isNull())
{
return;
}
pixmap = pixmap.scaled(460, 580, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QGraphicsScene* scene = new QGraphicsScene(this);
ui->gPhoto->setScene(scene);
QGraphicsPixmapItem* item = (QGraphicsPixmapItem*)scene->addPixmap(pixmap);
ui->gPhoto->fitInView(item);
}
The above code works, but the scene is actually newed everytime. Will the old scene be deleted automatically everytime?
I tried to make the scene as a fixed member variable, and try to clear the scene / remove items from the scene before adding new items, but all the tries failed to work (there’s either memory errors that cause the program to crash or the pictures can’t be loaded successfully). The only working solution is to new the scene each time.
Thanks.