Search code examples
c++qterror-handlingqwidgetnull-pointer

Should I check for null pointers after calling Qt's setui method?


I am using the Qt Designer to generate lots of different *.ui files for my application. Those files then get used following the single inheritance approach.

After calling ui.setupUi(this); do I need to check and see if any GUI elements are null? I know that setupUi goes and creates the instances of all the objects in the GUI but it returns void and doesn't seem to use exceptions. Is there some kind of guarantee I'm missing from Qt that lets me know UI elements are safe to use or should I be doing a null check every time I want to touch them?

An example can be seen in the sample code from the documentation here: https://doc.qt.io/qt-5/qtdesigner-calculatorform-example.html

Note that no null checking is performed before using the pointers to the UI elements. This could have been omitted for brevity of the example, but I don't ever see it in the sample code. If I can safely assume that the UI elements exist I can remove a lot of if statements from my code...


Solution

  • After calling ui.setupUi(this); do I need to check and see if any GUI elements are null?

    No. You don't need to do that.

    setupUi() does not swallow exceptions. It doesn't have any try blocks in it at all. (In Creator, you can just press F2 when the cursor in on the setupUi() call to jump to that function and inspect it.) If new throws, or one of the widget constructors throws, you will get that exception. AFAIK, the QWidget constructors will not throw, but new might (out of memory, for example.)

    You don't even need to check for exceptions yourself inside your own constructor that calls setupUi(). If setupUi() throws, then in turn your own constructor will automatically re-throw the exception.

    Anyway, long story short, all this means that you never need to check if any of the ui widget pointers is null.