Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt memory leak using QPixmap

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);
}
like image 659
user3241316 Avatar asked Feb 22 '26 14:02

user3241316


1 Answers

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.

like image 54
vahancho Avatar answered Feb 24 '26 03:02

vahancho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!