Thursday, October 10, 2013

Parenting in Qt

Qt has the concept of parenting the widgets. The reason is  to arrange the widgets in a hierarchical manner.
This way you can access / find almost all child widgets using a pointer / object of the parent.

The reason I'm highlighting it here is that when you are trying to generate the UI at runtime, this ability of able to find almost any widget comes in very handy.

Recently I had to work on a small utility which basically used an external configuration file to generate the contents of a form dynamically. The external file would contain the field definition and the constraints and I would create a corresponding widget and assign it the properties.

Now to access these, I didn't even have any pointers since everything was getting generated dynamically, I used the object names.

I assigned them object names that would correspond to the data that was contained in them. Then I would use findChildren method to get the matching objects.

But you didn't hear anything about parenting here. So why parenting is so important. See, even I didn't know it. But when I ran the binary through valgrind, I saw that my good enough code is leaking like a shipwreck.

So after going through a lot of internet posts and fair amount of qt documentation, I learned that When you delete a parent widget, all its Childs are automatically deleted'.  This translates do no more memory leaks. So after spending some more time getting my concepts right, I dug in. After a stressful evening of lot of cussing and keyboard banging, I got it right. All Child widgets properly coded to have appropriate parents and proper validity and existence checks along with some clever coding made the binary leak free!!!

Isn't it awesome when such a simple thing like parenting the widgets helps in such a big way!

No comments:

Post a Comment