Solved call parent function from child member
-
@mzimmers if Child has an instance or a pointer of Parent, you can. You have to set it. What is the error message?
-
@mzimmers
Wot? :)Assuming you are intending to use
QObject
parentage. Right??In
Child
:void setParentInt(){ qobject_cast<Parent *>(parent())->setInt(55); }
In
Parent
:Child child(this); // Or child.setParent(this);
And before anyone else says, what you are trying to do is likely to be sinful. You probably aren't a parent with a child, because if you were you would know that you would never allow your offspring to directly access anything in yourself (e.g.
parent->takeMoneyFrom()
).... -
@JonB said in call parent function from child member:
And before anyone else says, what you are trying to do is likely to be sinful....
Yeah, I kind of figured I was trying to perform an unnatural act here.
In my real application, I'm trying to incorporate a JSON parser class that I wrote into my various data models. With the parser object, I need to change values of members in my model(s). That's what I was trying to accomplish here.
-
@JoeCFD (I edited the code above) the error is "no member named 'setInt' in 'QObject'."
I think I'm taking a bad approach to this...
-
@mzimmers
The code shows how you would do your access to parent. It's the same principle even if you have some other kind of parentage thanQObject::parent()
, that's not the point though, same would apply for any classes you choose. But it's not a good idea. Low-level child objects (like your JSON parser) should not be going up the tree and changing higher-level things (like a model).One general possibility Qt offers is to have the child object emit a signal which the parent chooses to slot onto and adjust its things accordingly. Doesn't mean that's necessarily best here though.
You should look at rearchitecting :)
-
@JonB OK, that's what I wanted to know. Thanks for the ratification.
-
-
void setParentInt(){ if ( nullptr != qobject_cast<Parent *>(parent()) ) { /* better check first */ qobject_cast<Parent *>(parent())->setInt(55); } }
-
@JoeCFD
I deliberately chose to let it "crash" ifparent()
isnullptr
or not aParent *
, as that corresponds to the original "spec" and what the OP wrote. Of course any error checking desired can be added. -
@JonB OK. Better to have some log info here.
-
Unless I'm misreading the thread, there is a fundemental difference between a class trait object and an inherited class. you can't get "parent" of a trait object and expect it to be the class where the trait is instantiated.
When using pure inheritence, you can refer to parent(), but you better use the correct type cast operation when doing so.
IOW, parent or superclass access works for is_a, but not for has_a.