Is it good practice to use values from a derived item in QML from within the parent item?

Viewed 40

Is it good/acceptable practice to reference an Item in a "derived" component from a "parent" component in QML? Like so:

// Parent_Component.qml

Item {
    width: top_item.width
    height: top_item.height
}

// Derived_Component.qml

Parent_Component {
    Top_Item {
        id: top_item
        width: 500
        height: 500
    }
}

Is it just an issue of making sure that any component that inherits from Parent_Component has an Item called "top_item" or are there other reasons why this might be a bad idea?

EDIT:

More specifically, what I'm looking to do is place initialization (signal connection) code in the parent component that depends on objects in the child component. This makes the child components a lot cleaner by avoiding repeating the same code over and over. Here is a more specific example:

// Parent_Component.qml

Item {
    id: root
    signal initialize()
    signal button_clicked()
    signal close()
    
    Component.onCompleted: {
        root.initialize.connect(top_item.initialize)
        root.button_clicked.connect(top_item.button_clicked)
        top_item.close.connect(root.close)
    }
}

// Derived_Component.qml

Parent_Component {

    Top_Item {
        id: top_item
        anchors.fill: parent 
    }
}


1 Answers

The example you use is rather abstract. Since it only talks about width, height, we can only go so far, but, in terms of blackboxing we should talk more about exposing properties (and, or signals, etc). In your case, a simple change would achieve that:

Parent_Component {
    width: top_item.width
    height: top_item.height

    Top_Item {
        id: top_item
        width: 500
        height: 500
    }
}

We can get it into a bit more, but you need to come up with better examples of what you are trying to achieve.

Related