I want to show a image on qt label. I am getting image data in the form of QByteArray and I am loading it into label. Below is the code :

defined in constructor

QPixmap *pixmapTest;
pixmapTest  = NULL;

the following code is in a function which is getting called multiple times :

    RequestCompleted(QNetworkReply *reply)
{
if(pixmapTest){
    qDebug()<<"delete showImage Pixmap Object";
    delete pixmapTest;
    pixmapTest = NULL;
}
pixmapTest = new QPixmap();
QByteArray jpegData = reply->readAll();
pixmapTest->loadFromData(jpegData);
ui.qtLabel->setPixmap(*pixmapTest);
}

After calling this function for around 500 times I am getting this error

QImage: out of memory, returning null image.

I am not getting what is the error in the above code. Can someone please tell me how to solve this?

2

There are 2 answers

0
frogatto On

First off allocating and de-allocating memory for a variable (pixmapTest) in a function that gets called many times doesn't make sense enough. You should allocate the memory first and once all is done de-allocate it. For example:

pixmapTest = new QPixmap();

for(size_t i = 0; i < 1000; i++){
    // Call that function
}

delete pixmapTest;

Apart from this, it sounds like your app is leaking memory. Note that by deleting the pixmapTest, you're not deleteing the memory jpegData points to. Therefore, in each function call you should take care of the memory to which jpegData points.

3
Kuba hasn't forgotten Monica On

Most likely, you're not freeing the reply itself.

There's also no need to store the pixmap, nor to manage it through a pointer. Keep it by value, and assign new value each time you receive a reply.

E.g.:

class MyClass : public QWidget {
  Q_OBJECT
  Ui::MyClass ui;

  explicit MyClass(QWidget *parent = nullptr) : QWidget(parent) {
    ui.setupUi(this);
  }

  Q_SLOT void requestCompleted(QNetworkReply *reply) {
    QPixmap pix;
    pix.loadFromData(reply->readAll());
    ui.qtLabel->setPixmap(pix);
    reply->deleteLater();
  }
};