Qt memory leak using QPixmap

I am getting weird memory leak somewhere in this code. A method is a SLOT associated with a method in another thread. It does 2 things: 1 it updates the textbox with iteration that another thread is on. 2, it updates the image displayed in the GUI to the image corresponding to this iteration.

It works fine for 10-30 iterations, then blows up. Observing memory usage in Task Manager, I can see that it is stable at first, and 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 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);
}

      

+3


source to share


1 answer


I think you are not just updating your image, but creating a new pixmap for 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 elements in your scene. I think you need to update the existing one QGraphicsPixmapItem

with the function QGraphicsPixmapItem::setPixmap()

instead of creating a new one on each iteration.

+5


source







All Articles