View Full Version : Dynamic type of parent outside the constructor

25th March 2011, 21:29
Hi guys, I have a question. I'm making a widget (let's call it myWidget) which inherits from QWidget and my window widget (the top one in the parent hierarchy) is a MainWindow (made by me) which inherits from QMainWindow. The question is, why something like this doesn't work ?

class myWidget : public QWidget {
myWidget(QWidget* parent =0) {}

// a slot I made
void myslot() {
MainWindow* p = static_cast<MainWindow*>(window());

The cast doesn't work, even with a dynamic_cast its the same. Why ?

25th March 2011, 22:15
It's not quite clear what's goin on here.I mean,how does MainWindow class relate to myWidget class?What does the slot belong to? Maybe i didn't understand the class hierachy right but by now,it seems like you're trying to cast essentially inappropriate types...

26th March 2011, 07:30
Ah sorry I think I figured out what's going on. I thought that the function window() would return the top level widget in the parent hierarchy, whereas it returns the first window widget in the hierarchy. So it was a bad type cast. By the way, is there any built-in function that returns the top level widget ? I mean, something like

QObject* top_level_widget(QObject* q) {
q = q->parent();
return q;