1
votes

I have this in a file named ChildItem.qml:

Item{
    property var childProperty
}

In another file named ParentItem.qml, I create the parent item and try to bind the childProperty to a property of the parent:

Item{
    property ChildItem childItem: null
    property var parentProperty
    childItem.childProperty: parentProperty
}

In main.qml I instantiate both objects and bind the parent's reference to the child:

ApplicationWindow{
    ChildItem{
        id: childID
    }
    ParentItem{
        id: parentID
        childItem: childID
    }
}

This gives me a Cannot assign a value directly to a grouped property error on the childItem.childProperty: parentProperty line. I work around this by changing the parent as follows:

Item {
    property ChildItem childItem: null
    property var parentProperty
    //childItem.childProperty: parentProperty
    onParentPropertyChanged: childItem.childProperty = parentProperty
}

But this looks and feels very artificial. Are there better ways to do this or other suggestions to change the structure in another way?

2

2 Answers

1
votes
childItem.childProperty: parentProperty

That's unfortunately not possible in QML syntax, even though it would be nice. The limitation is that bindings can only be defined within the declaration of the element itself, e.g. in this case within ChildItem { ... }. As a workaround, the Binding element can be used in other places:

Binding {
    target: childItem
    property: "childProperty"
    value: parentProperty
}

But that, admittedly, is quite unwieldy as well.

I'd probably try to change the structure of my QML to avoid getting into this situation in the first place, maybe something like this:

ApplicationWindow{
    ChildItem{
        id: childID
        childProperty: parentID.parentProperty
    }
    ParentItem{
        id: parentID
    }
}
-1
votes

Ok, you have several errors in the code. Both logical and syntactical ones.

childItem.childProperty: parentProperty

This line isn't allowed here because of mixing declarative and imperative code. Also what will be if childItem is null? Replace it with:

onChildItemChanged: { 
    if(childItem)
        childItem.childProperty = parentProperty;
}

Next error:

childItem: childId

Just replce childId with childID.