Reputation: 251
I try to access parent from a child.
Parent and Child class inherits QWidget
Let see:
//parent.h
public:
child* h_child = nullptr; //pointer to child - now i can control child in parent methods
//method in parent.cpp
h_child = new child(); //show child window
h_child->show(); //show next window
And child
//child.cpp in child method
parent_class *sth = qobject_cast<parent_class*>(parentWidget());
if (sth == NULL){
QMessageBox::warning(this, "error !", "error!");
}
And ofc i saw 'error'
parentWidget()
with this->parent()
. // result the sameI try to run child instance like that:
h_child = new child(this); //show child window
But when i try to use h_child->show()
the window which is showed is 'broken' (i have window in window(child window in parent window , without child window frame) - it looks illegibly)
So how can i access to parent methods and variables ?
Upvotes: 1
Views: 3963
Reputation: 336
As the others already stated, you need to set the parent of the child in the constructor.
If you pass this
as parent and your widget/window looks broken afterwards, it is probably a layout problem. Do your widgets have a layout and do you add the child
to the layout of the parent
?
Upvotes: 0
Reputation: 902
To set the parent of a widget you can do this:
widget = new Widget( parent );
or this:
widget->setParent( parent );
of course if you try to show a widget without parent, it is shown with their own window border.
When you implement new widget you shall "propagate" parent pointer form constructor:
class Widget : public QWidget
{
public:
Widget( QWidget* parent ) : QWidget( parent )
{ }
};
If you forget this step, base Qt widget doesn't notice the assignment and this widget will not have valid parent.
Upvotes: 1
Reputation: 13238
After you create your child do you set your parent to be the parentWidget? Normally, when you create QWidget
you pass parent to the constructor, but in your code I see that child()
constructor does not have any parameters. That's why parentWidget()
returns NULL
, you just don't set it anywhere.
Upvotes: 2