Qt图形视图,显示图像! ,窗口小部件
问题描述:
这里是我的代码:Qt图形视图,显示图像! ,窗口小部件
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();
}
}
我想从文件显示的图像,代码工作正常,但图像disappiars非常快。
如何暂停图像屏幕?
如何在“graphicsView”小部件中加载图像?
我的代码:
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();
}
}
它不工作。
如何解决这个问题?
答
您需要创建在堆上的所有对象,否则当他们走出去的范围,他们被删除:
QGraphicsScene* scene = new QGraphicsScene();
QGraphicsView* view = new QGraphicsView(scene);
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(item);
view->show();
你的第二个问题可能与 - scene
分配给ui->graphicsView
,但它被立即删除之后,再次在堆上创建所有对象。
答
如果你不需要坚持使用QGraphicsView,可以使用QLabel代替。我没能解决它的QGraphicsView ...
QString filename = "X:/my_image";
QImage image(filename);
ui->label->setPixmap(QPixmap::fromImage(image));
+0
这是最慢和过度操作。 –
而如何避免内存泄漏? :=)我必须释放内存权? :) –
是的,你需要清理自己与删除。我建议你声明你的QGraphicsScene(和QGraphicsPixmapItem,如果它不在additem期间被复制)作为类指针变量。然后我会建议你在声明变量时使用某种智能指针,例如QSharedPointer: QSharedPointer ptr_scene; this-> ptr_scene = QSharedPointer (new QGraphicsScene()) 然后当MainWindow关闭时管理内存。 –
thomas