Unsolved QML ListView: center current item
-
Consider a simple horizontally-oriented ListView with a small caveat: items have different widths. We can easily make the currentItem - when flicked - to automatically snap to an arbitrary position (preferredHighlightBegin, preferredHighlightEnd and highlightRangeMode in the code below). This works with fine when item's left border is in question, however there is no easy way to snap to item's center.
I've tried several solutions but none of them works smoothly enough. Any ideas?
import QtQuick 2.7 Item { width: 600 height: 100 ListModel { id: myModel ListElement { w: 100 } ListElement { w: 50 } ListElement { w: 200 } ListElement { w: 50 } ListElement { w: 20 } } Rectangle { id: wrapper width: parent.width height: parent.height ListView { id: view anchors.fill: parent spacing: 15 model: myModel orientation: ListView.Horizontal delegate: Item { width: w height: parent.height Rectangle { anchors.centerIn: parent width: parent.width height: parent.height color: "cyan" Text { text: index anchors.centerIn: parent } } } preferredHighlightBegin: width / 2 preferredHighlightEnd: width / 2 highlightRangeMode: ListView.StrictlyEnforceRange // One possible solution - but produces strange 'jerking' repositions onCurrentItemChanged: { wrapper.x = -currentItem.width / 2 } } } }
-
Do you mean something like this?
preferredHighlightBegin: width /2 - currentItem.width /2 preferredHighlightEnd: width /2 + currentItem.width /2
-
@J-ATP This causes a Binding loop