Handling Multiple Forms in Qt Creator

Before I go on with this post, allow me to say Happy Holidays to everybody around SX. Make sure to spend time with significant others if at all possible.

Now that I have that out of the way, I spoke about my initial impressions of Qt Creator as I have done some side practice with it along with working on the GUI and some aspects of the OFACE backend. (One of the major parts will most likely be worked on this Friday and if there is enough demand, I may do a timelapse video of my codework.) For those who may have read my basic programming concepts tutorials, I talked about basic memory allocation in C++ and how this is good to know for C++ and in many cases other languages regardless of if they use a garbage collector. Well, in Qt Creator I have been working with how to handle multiple forms. Now, in the case of something like C# within the .NET framework, this is a pretty cut and dry task. However, this is a different ballgame when it comes to Qt Creator.

Adding the form in question only requires a Qt Designer Form Class to be added to the project, but doing this doesn't just mean that it can be called and all is good. When this is done, the ui, header, and cpp files are created for the class and if the class is dynamically allocated without deleting the memory after the object is no longer in use, the end result will be a textbook entry level memory leak. At the same time, calling a new form up from a method that is used for a signal event does not allow for such deletion to happen immediately as it would immediately close the form. Fortunately, there is a good way to handle this.

As forms inherit the QDialog class in Qt Creator, the easiest way to handle this is to override the closeEvent() virtual function. From this, using the line "delete this" will use the this keyword to tell it to delete the form in question. The end result is that the form will free the memory in question when it is closed and stop memory leaks without many issues. Now, some people may consider this to be a duh tip, but the reality is that most of the examples that I have seen for Qt Creator do not do this in any way, shape, or form and I find this to be legitimately troubling.

Overall, this is a really simple, but effective trick that I have found to handle freeing up memory when a form object in Qt is dynamically allocated. The reality is though that many people do not think of stuff such as this. The end result is that many programs may have unnecessary memory leaks that are going un-handled. While the leak would be minor, I personally would rather have a stronger quality product overall and take this precaution.