tags:

views:

165

answers:

2

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.

+2  A: 

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();
}
Kyle Lutz
The symbol 'parent' must be replaced with a call to either parentWidget() or parent() in order for this code to compile. This is because 'parent' is only valid in the scope of the constructor, while the question asks how to call doSomething() from secondClass::doSomethingElse().
Gareth Stockwell
+1  A: 

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 );
}
Caleb Huitt - cjhuitt