mimic
mimic

Reputation: 5224

How can I determine if a dialog is null in Qt?

I'm trying to show a simple dialog like this:

if (!aboutDialog)
        aboutDialog = new AboutDialog(this);
    aboutDialog->exec();

For some reason it doesn't work (aboutDialog has some pointer although is not initialized), the checking if (aboutDialog == 0) doesn't work either. I don't want to create the instance every time, but only once. How do I check this properly?

Thanks!

Upvotes: 2

Views: 2526

Answers (2)

Mat
Mat

Reputation: 206659

You need to initialize aboutDialog to 0 explicitly somewhere. Probably in the constructor of the class this member belongs to.

(!aboutDialog) is a correct test.

Consider the following:

#include <iostream>

class Thing {
  void *data;
  public:
    Thing(){}
    void print() {
      std::cout << data << std::endl;
  }
};

int main()
{
  Thing t;
  t.print();
  return 0;
 }

Try to compile that and run it multiple times. Chances are it will print something different each time. Why? Because data is uninitialized. It contains garbage. It has as much chance of being a null pointer than 0x1234ABCD or 42.

To fix it, data needs to be initialized somewhere. The simplest way here is just to do that in Thing's constructor like below:

Thing() : data(0) {}

Upvotes: 2

user89862
user89862

Reputation:

My answer is probably not the best :) I use Qt with python, where you (in python) can write new attributes to a class whenever you want to "from the outside". If possible, I'd set a variable (again, maybe not the best practice) to some value when you construct aboutDialog. Then you can check if this is set later on. Like a state variable or something :)

Upvotes: 0

Related Questions