ListView showing a constant number of items despite of it's height



  • Hi all,

    I want a ListView to show only a particular number of it's items no matter what the height of the ListView is. To get this I set the height of each item to the height of the ListView divided by the number of visible items. That works so far.
    I have an issue with the time it takes to create this ListView (startup time). While populating the ListView with it's delegates ListView.view.height seems to be 0 what causes the ListView to create all 10000 items, cause they all fit into the view. Afterwards the ListView.view.height gets it's actual value and 9996 items get deleted again.
    Here's my code:

    ListView {
      anchors.fill: parent
      cacheBuffer: 0
      model: 10000
      property int visibleItemsCount: 4
      delegate: Text {
        width: ListView.view.width
        height: ListView.view.height / ListView.view.visibleItemsCount
        text: index
        Component.onCompleted: console.log("c", index)
        Component.onDestruction: console.log("d", index)
      }
    }
    

    What can I do to get the ListView to only create visibleItemsCount number of items?



  • There is no direct way to this as the model is definited with count. Either u use proxy model and try controlling items or try exposing model through c++ side and update model with required number of elements.



  • You could check if the height of the listView is null and return a sensible height if that's the case.
    height: ListView.view.height ? (ListView.view.height / ListView.view.visibleItemsCount) : implicitHeight



  • @GrecKo Thank you very much! Your solution led my girlfriend to an idea which inspired me to the following perfectly working solution:

    height: (ListView.view.height || 1) / ListView.view.visibleItemsCount
    

    I would call it a bug of ListView to put all (!) elements of the model into the view if the view's and the delegates's height both are 0.
    Thanks again!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.