Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ QtQggraphicsView修复ram使用_C++_Qt - Fatal编程技术网

C++ QtQggraphicsView修复ram使用

C++ QtQggraphicsView修复ram使用,c++,qt,C++,Qt,我正在使用QGraphicsView使用以下语句加载图像: if (QFile().exists(pl)){ Sleft = new QGraphicsScene; Sleft->addPixmap(pl); ui->left->setScene(Sleft); ui->left->show(); ui->left->update(); } if (QFile().exists(pr) && (pr

我正在使用QGraphicsView使用以下语句加载图像:

if (QFile().exists(pl)){
    Sleft = new QGraphicsScene;
    Sleft->addPixmap(pl);
    ui->left->setScene(Sleft);
    ui->left->show();
    ui->left->update();
}
if (QFile().exists(pr) && (pr != "")){
    Sright = new QGraphicsScene;
    Sright->addPixmap(pr);
    ui->right->setScene(Sright);
    ui->right->show();
    ui->right->update();
}
else {
    scene3 = new QGraphicsScene;
    ui->right->setScene(scene3);
    ui->right->show();
}
Sleft、Sright和scene3声明为

QGraphicsScene* Sleft;
QGraphicsScene* Sright;
QGraphicsScene* scene3;

我试图弄清楚为什么RAM的使用量不断增加,以及如何解决它。我想这可能与我每次调用该方法时都重新输入变量有关。

问题在于每次加载图像时都会创建一个新的
qgraphicscene
和一个新的pixmap项,但不会破坏旧场景和旧pixmap项

无需在每次加载图像时创建新场景。您可以在启动时为每个
QGraphicsView
创建并设置一个
qgraphicscene

要加载新图像时,可以使用
qgraphicscene::addPixmap
并将返回的
QGraphicsPixmapItem
指针保存到类变量中。如果图像已加载,则必须首先使用
delete
将其卸载


我建议您在C++中学习更多关于内存分配的知识。

是否每次要加载映像时都要创建一个新的QGraphicscene?我想是的。每次调用函数时都会声明场景。我无法让场景表现为全局变量……你确定要在堆上制作QGraphicscene吗?我认为该类型是智能指针的包装。无论如何,您永远不会删除任何QGraphicsCenes。当我进行QT开发时,我不记得必须删除QT类型,它们通常是为我管理的。我以前尝试过这样做,只是因为我无法通过声明为全局变量来实现它的行为,QGraphicsView将变为空白。我曾尝试过
删除Sleft
,但由于它将在函数中声明,因此无法在函数外部访问。很抱歉,我无法撤消,也许您可以发布更多代码。但是,您可以将变量(例如,两个场景指针和项目指针)声明为类变量。基本上,我需要将图像加载到qgraphicsview中,然后在调用另一个函数时将其删除,以便加载另一个图像。如果未删除场景对象,则会导致内存泄漏。