Qt memory leak using QPixmap

2019-05-11 06:56发布

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.

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

The SLOT in question:

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

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-11 07:17

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
    [..]
}

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.

查看更多
登录 后发表回答