使用QPixmap的Qt内存泄漏 [英] Qt memory leak using QPixmap
问题描述
我在这段代码中的某处遇到了一个奇怪的内存泄露。该方法是一个SLOT连接到另一个线程中的方法。它做2件事情:1它更新一个文本框与另一个线程的迭代。 2,它将GUI上显示的图像更新为与该迭代相对应的图像。
I'm getting a strange memory leak somewhere in this code. The method is a SLOT connected to a method in another thread. It does 2 things: 1 it updates a text box with the iteration that that the other thread is on. 2 it updates the image shown on the GUI to the image corresponding to that iteration.
它适用于10-30次迭代,然后爆炸。在任务管理器中看到它的内存使用,我可以看到它的稳定,然后每次迭代增加RAM使用量约10%。
It works great for 10-30 iterations, then blows up. Watching its memory usage in the task manager, I can see that it's steady at first, then each iteration increases the RAM usage by about 10%. What can I do to remove the leak?
Transition::Transition(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Transition)
{
ui->setupUi(this);
this->files = files;
imageObject = new QImage();
scene = new QGraphicsScene(this);
}
Transition::~Transition()
{
delete ui;
delete imageObject;
delete scene;
}
有问题的SLOT:
void Transition::onCounterChanged(QString counter){
ui->imageCounter->setText(counter);
foldername = ui ->folderName->toPlainText();
int m = counter.toInt();
QString filename = files[m];
imageObject->load(filename);
image = QPixmap::fromImage(*imageObject);
scene->clear();//THIS FIXES THE LEAK
scene->addPixmap(image);
ui->picDisplay->setScene(scene);
ui->picDisplay->fitInView(image.rect(),Qt::IgnoreAspectRatio);
}
推荐答案
更新您的图像,但创建新的像素映射项目到场景:
I think you do not simply update your image, but create new pixmap item to the scene with:
void Transition::onCounterChanged(QString counter)
{
[..]
imageObject->load(filename);
image = QPixmap::fromImage(*imageObject);
scene->addPixmap(image); // <----- Adds new pixmap item to the scene
[..]
}
所以,10-30迭代后,你有10-30像素映射项目在你的场景。我想,你必须更新现有 QGraphicsPixmapItem
使用 QGraphicsPixmapItem :: setPixmap()
函数,而不是创建一个新的每次迭代。
So, after 10-30 iterations you have 10-30 pixmap items on your scene. I think, you have to update existing QGraphicsPixmapItem
using QGraphicsPixmapItem::setPixmap()
function instead of creating a new one on each iteration.
这篇关于使用QPixmap的Qt内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!