Search code examples
qtqt4parent

Qt4 parent pointer usage


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

  • 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();
    }