Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
parent() not returning the "parent" QWidget given to constructor, why?
DasCapschen last edited by
I have a problem, the parent() function does not return the same object that I passed into the constructor. Thus, when I
((MainWindow*)parent())->function();I get a segfault... not nice...
so I checked why this happens with a bunch of qDebug()s... this is what I got...
MainWindow Contructor, this == 0x7ffc53ce97f0 FileList Constructor, parent() == 0x7ffc53ce97f0 FileList Function, parent() == 0x557b8c8c9170 parent()->parent()->parent()->parent()->parent() == 0x7ffc53ce97f0
so... where do 4 parent objects come from, that I never created? And it seems they only spawn into existance AFTER my constructor ran... so it's not like it's the superclass constructor that causes this...
I mean I guess I could just save the parent I give to the constructor as a member variable (or just call parent() five times...), but doesn't that kind of defeat the purpose of parent()?
I'd like to know, WHY does this happen? And what can I do about it?
this depends on your code.
If you call QMainWindow::setCentralWidget() for example your widget is reparented. No matter what parent you passed at construction time
VRonin last edited by
WHY does this happen?
Layouts and container widgets re-parent anything that is passed to them.
And what can I do about it?
Good OOP design works as a 1 way tree, the parent knows about the child but the child assumes and knows nothing about the parent so
((MainWindow*)parent())->function();is very bad design. the child should emit a signal and the parent should connect to that signal to run the
As the others says, this should be done via signal and slots for a much better design.
However, the cast is also suboptimal and dangerous. ( as your segfault tells you :)
This will not crash if parent is not what you think.
MainWindow* mywin = qobject_cast<MainWindow* > ( parent() ) ; if (mywin) mywin->function();