Memory Leak due to Qt Designer components/widgets
-
HI, I'm now using Qt designer to create an application , however there's some memory leak according to vld,
which shows that the components are not being deleted
I traced in and shows:
painter2 = new QPainter(this); is the reason of my promoted labelvoid MyLabel::paintEvent(QPaintEvent *event) { QLabel::paintEvent(event); QPainter painter(this); painter2 = new QPainter(this);// Painter(this); painter.setPen(QPen(Qt::green, 2)); if (show) { if (m_rectStartPoint != m_rectEndPoint && (mouse_pressed == true || mouse_released == true)) { painter.drawRect(QRect(m_rectStartPoint, m_rectEndPoint)); } } else { } }
I've checked and not sure is it a setparent problem, cause qlabel should already compiled and set parent automatically by Qt designer .ui file.
(My main window and subwindow also have the same problem, set parents not working for them, am I supposed to delete them by myself? Thought they should be automatically deleted by Qt)
-
Hi,
@Puppy-Bear said in Memory Leak due to Qt Designer components/widgets:
painter2 = new QPainter(this);// Painter(this);
You are allocating a new QPainter on each call to paintEvent which can happen quite a lot.
This wrong on two levels:
- you never delete that object
- it's only useful in the paint event method so there's no need to allocate it on the heap.
-
Hi,
QObjects
get destroyed together with their parent.The parent has nothing to do with whether you use an UI file or not.
-
@Puppy-Bear said in Memory Leak due to Qt Designer components/widgets:
painter2 = new QPainter(this);// Painter(this);
@Bonnie is right regarding parenthood. Please take a look at the documentation.
-
@Puppy-Bear said in Memory Leak due to Qt Designer components/widgets:
painter2 = new QPainter(this);// Painter(this);
What's the reason for this line? You already created a QPainter object on the stack (painter) and that is the QPainter object that you used to perform paint operations.
-
Hi,
@Puppy-Bear said in Memory Leak due to Qt Designer components/widgets:
painter2 = new QPainter(this);// Painter(this);
You are allocating a new QPainter on each call to paintEvent which can happen quite a lot.
This wrong on two levels:
- you never delete that object
- it's only useful in the paint event method so there's no need to allocate it on the heap.
-
@Bonnie said in Memory Leak due to Qt Designer components/widgets:
QPainter
does not subclass fromQObject
, so there won't be something like "parent" to it.oops... forgot about that :)
Yeah, the usual way is to not
new
aQPainter
inpaintEvent
, but allocate on stack, simply use it and let it go out of scope (like shown inQPainter
documentation examples).