PDA

View Full Version : Access parent's function from child widget



el33t
15th March 2011, 20:33
I want to access a function in my parent from a child widget.

This is the code of the parent widget:

mainwindow.cpp

#include <QtGui>
#include <iostream>
#include "mainwindow.h"
#include "menu1.h"



mainwindow::mainwindow()
{
men = new menu1(this); // This is the child widget

qs = new QStackedWidget(this);
qs->addWidget(men);
qs->setCurrentIndex(0);
}

mainwindow::functions1()
{
std::cout<<"function called";
}

Here is the code of the child widget.

menu1.cpp

menu1::menu1(QWidget *parent) :
QWidget(parent)
{

resize(880,558);

}

Now, I want to access funtion1 from 'men'. How do I do it?

I tried the following in men.cpp but got errors:

1) parent->funtion1();

This gives the error: 'class Qwidget' has no member named 'funtion1'

2) parent->parent->funtion1();

This gave the error : invalid use of member (did you forget the '&')
base operand of '->' is not a pointer


Any help would be appreciated.

Regards,

wysota
15th March 2011, 22:20
Either cast the parent pointer to the right type or store the pointer to the parent somewhere in the child when receiving it in the constructor. Or use signals and slots.

el33t
16th March 2011, 03:13
Either cast the parent pointer to the right type or store the pointer to the parent somewhere in the child when receiving it in the constructor. Or use signals and slots.

Ok, I'll try the casting.

But why is 'parent()' not working? Isin't it doing the same thing (pass the parent pointer) ?

conner686
16th March 2011, 04:58
Ok, I'll try the casting.

But why is 'parent()' not working? Isin't it doing the same thing (pass the parent pointer) ?
The return value of `parent()` is `QObject*` by default, not `mainwindow*`. As such, you do not have access to `mainwindow` functions, even though you're pretty sure that's what type of object you actually have. That's why the cast is neccessary; it tells the compiler that even though you have a `QObject*`, it should be treated as a `mainwindow*` and let you call those functions as normal.

el33t
16th March 2011, 14:20
Did the casting an everything worked like a charm. Thanks a lot for the assitance guys!