PDA

View Full Version : QImage deconstructor or delete / proper usage



chrisbay90
14th July 2015, 08:13
I have a serious memory leak due to what I beleive to be a new instance of QImage being created but not deleted in the memory every time a function is called. My code looks somewhat like this.



//myClass.cpp

// Public Function, called iterativly each frame
void myClass::updateAndPaint(int **arr, float **arr2, int arrSize, int arr2Size, char type)
{
// Do stuff here
update();
}

// Private function
void myClass::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rec = boundingRect();
QImage image(width, height, QImage::Format_RGB32);

// Do stuff here
image.setPixel(x, y, thisPixel);
// Do stuff here

painter->drawImage(rec, image);
}


However if I make the QImage declaration global in the .h file like so


// myClass.h
QImage *image;


Then add this to the constructor


myClass::myClass(int height, int width)
{
image = new QImage(width, height, QImage::Format_RGB32);
// the rest of my constructor
}


At any reference of the QImage object `image` in the paint function the compiler throws an error as such
error C2228: left of '.setPixel' must have class/struct/union

How instead should I be using QImage?

Ginsengelf
14th July 2015, 09:06
Hi, if you use a pointer, you need to use image->setPixel().
But your original code should not create a memory leak because the QImage is created on the stack and gets destroyed once the method myClass::paint() is left.

Ginsengelf

d_stranz
14th July 2015, 20:01
I'll make a pretty good bet that it is the "do stuff here" code that causes the memory leaks unless



image = new QImage(width, height, QImage::Format_RGB32);

this code also ended up inside the paint() method.