qtqmlqt5.8

ChildrenRect always returns 0


I have a Flickable item in where I want to put a customized flow component, so I created the Flickable like this:

import QtQuick 2.0
import UICore.Layouts 1.0 as Layouts
Flickable{
    anchors.fill: parent;
    contentWidth: parent.width;
    contentHeight: flow.childrenRect.height;

    Component.onCompleted: {
        console.log("The content height is: " + contentHeight);
    }


}

Then in my main.qml I have this (The file above is MyFlickable, and the MyFlow is a flow with specific properties):

 MyFlickable{
        ....
        MyFlow{
            id: flow
         ... 
        }
  }

This works great but the problem is that I want to be able to reuse this item with as little overhead as possible. Setting the id inside of my MyFlow doesn't work, and I tried this

contentHeight: contentItem.childrenRect.height

as suggested in here under contentWidth section: http://doc.qt.io/qt-5/qml-qtquick-flickable.html#contentItem-prop

but that always returns 0. I've tried a couple of other ways to receive onCompleted signals but I get the same luck. This doesn't work for example:

contentHeight: children[0].childrenRect.height

Which in my mind should be the same as accessing the item through the id, bu apparently not.

So my question is: how do I get to height of my flow after all the components have been added?

Thanks in advance!


Solution

  • This wlil achieve what you want:

    contentHeight: contentItem.children[0].childrenRect.height
    

    From Qt docs

    Items declared as children of a Flickable are automatically parented to the Flickable's contentItem. This should be taken into account when operating on the children of the Flickable; it is usually the children of contentItem that are relevant.

    But I must say it is bad practice for a component to make assumptions about things outside its own QML file, as it makes the component difficult to reuse. Specifically in this case the Flickable is making the assumption that its first child is of a Component type that makes use of the childrenRect property. Your MyFlow component does, but many other components do not, for example an Image.