Tutorial :Qt4 parent pointer usage



Question:

I'm having some problem with understanding usage of parent pointer in QT4.

class firstClass : public QWidget  {      Q_OBJECT    public:       firstClass(QWidget *parent = 0);      ~firstClass();        void doSomething();    private:      secondClass * myClass;  };    class secondClass : public QWidget  {      Q_OBJECT    public:      secondClass(QWidget *parent = 0);      void doSomethingElse();  };  

I want to call doSomething() method while running doSomethingElse(). Is there any way to do it using parent pointer?

I tried parent->doSomething() but it doesn't work. It seems that Qt Creator is suggesting only methods from QObject class after parent->.

On the other hand I can't write it like secondClass(firstClass *parent = 0); - compilator returns error:

Thanks for any suggestions.


Solution:1

If you are positive that the parent of secondClass is always going to be firstClass then you can do this:

static_cast<firstClass *>(parent)->doSomething();  

Alternatively you can use qobject_cast and check to make sure that parent is actually an instance of firstClass:

firstClass *myParent = qobject_cast<firstClass *>(parent);  if(myParent){      myParent->doSomething();  }  


Solution:2

The more Qt-ish way to do this would be to use signals and slots, instead of trying to directly call a different function.

class firstClass : public QWidget  {      Q_OBJECT    public:       firstClass(QWidget *parent = 0);      ~firstClass();    public slot:      void doSomething();    private:      secondClass * myClass;  };    class secondClass : public QWidget  {      Q_OBJECT    public:      secondClass(QWidget *parent = 0);      void doSomethingElse()      {          // ...          emit ( triggerDoSomething() );          // ...      }    signal:      void triggerDoSomething();  };    firstClass::firstClass(QWidget *parent) :       QWidget(parent), myClass(new secondClass(this))  {      // ...      bool connected = connect(myClass, SIGNAL(triggerDoSomething()),          SLOT(doSomething()));      assert( connected );  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »