Hello everyone! I understand from this topic that trying to add a listener to a child node of a ValueTree will not work, but then what is the solution ? How can I add listeners to specific children inside my tree and not to the parent node ? I don’t want callbacks going off all over the place just because I couldn’t isolate the specific relevant node. I could use std::unique_ptr<ValueTree> but that sounds very ugly. Or pass every node individually, on inside an Array, but that sounds very ugly too. Maybe i’m thinking things wrong ? How I am supposed to do this ? Thanks!
There is no issue with adding listeners to children (or grand-children), but the posting you linked does not work because of lifetime issues. With:
parent.getChild(0).addListener(listener);
A ValueTree is returned by getChild(), a listener is added to it, and then the ValueTree is destroyed. ie. the ValueTree returned is a copy of the child (well, a copy of the wrapper, not the data, and the wrapper is what holds the callbacks), not the child itself. If you kept that copy around, the listener would still exist. So,
auto child = parent.getChild(0);
child.addListener(listener);
Works, as long as child is in scope. If this is part of a class, you would need to have child as a member of the class so that it’s lifetime corresponds with the lifetime of the class.
Ok I get it, thanks !
EDIT: sorry, I got confused
I was getting mixed up with my trees, but the code below works perfectly well! The child tree was not valid, using child.isValid helped me to debug
Well I still have some issues and don’t really get it. This is what I understood and the code does not work :
class MyClass : public ValueTree::Listener { public: MyClass(ValueTree parent) { localParent = parent; localChild = parent.getChild(0); localChild.addListener(this); } void valueTreePropertyChanged (ValueTree &treeWhosePropertyHasChanged, const Identifier &property) override { // valueTree callback, I only want changes to the child tree to trigger this callback } ValueTree localParent; ValueTree localChild; }I don’t get it because
localChildis a member ofMyClassand it stays in scopeIf I change it and add the listener to
localParentinstead, the callback gets triggered, but that’s not what I want. Am I forced to pass references or pointers to the tree in this situation ? Thanks again!
Awesome! I have grown to really appreciate ValueTree’s, and use them pretty heavily these days to hold all kinds of data, keeping the coupling of code to a bare minimum.
