Qt图形视图,展示图片!窗口小部件。

15

这是我的代码:

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

我想从文件中显示图像,代码运行良好,但图像很快消失。

如何暂停图像屏幕?

以及如何在 "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();    
    }
}

它不起作用。

如何修复?

2个回答

25

你需要在堆上创建所有的对象,否则当它们超出作用域时会被删除:

QGraphicsScene* scene = new QGraphicsScene();
QGraphicsView* view = new QGraphicsView(scene);
QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(item);
view->show();

你的第二个问题可能与此相关 - scene 被分配给 ui->graphicsView,但它被立即删除了,所以再次在堆上创建所有对象。


1
如何避免内存泄漏?:=) 我需要释放内存,对吗?:) - Davit Tvildiani
2
是的,您需要使用delete进行清理。我建议您将QGraphicsScene(如果在additem期间未被复制)声明为类指针变量。然后,我建议您在声明变量时使用某种智能指针,例如QSharedPointer: <在类头文件中> QSharedPointer<QGraphicsScene> ptr_scene;<在源文件中> this->ptr_scene = QSharedPointer<QGraphicsScene>(new QGraphicsScene())然后,在MainWindow关闭时管理内存。 - thomas

8

如果您不必坚持使用QGraphicsView,则可以考虑使用QLabel。我无法解决QGraphicsView的问题...

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

1
这是最慢且过度的操作。 - Bahramdun Adil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接