中心 QML ListView 突出显示的项目
Center QML ListView highlighted item
图片Test
中,Test 1
和Test 2
在ListView
中。在这种情况下,Test
元素被突出显示。如何修改视图行为以确保当前(突出显示的)项目始终位于列表的中间?我想要达到的效果如下图所示:
您可以看看 ListView 的 positionViewAtIndex
方法,看看是否有帮助。
您只需要 highlightRangeMode
以及 preferredHighlightBegin
和 preferredHighlightEnd
。来自文档:
These properties affect the position of the current item when the list is scrolled. For example, if the currently selected item should stay in the middle of the list when the view is scrolled, set the preferredHighlightBegin and preferredHighlightEnd values to the top and bottom coordinates of where the middle item would be. If the currentItem is changed programmatically, the list will automatically scroll so that the current item is in the middle of the view. Furthermore, the behavior of the current item index will occur whether or not a highlight exists.
这里是水平 ListView
的完整示例,当前项目位于中心。
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
width: 300
height: 150
visible: true
ListView {
anchors.fill: parent
spacing: 5
model: 20
delegate:
Rectangle {
width: 30
color: ListView.view.currentIndex === index ? "red" : "steelblue"
height: ListView.view.height
Text {
anchors.centerIn: parent
text: index
font.pixelSize: 20
}
}
orientation: Qt.Horizontal
preferredHighlightBegin: 150 - 15
preferredHighlightEnd: 150 + 15
highlightRangeMode: ListView.StrictlyEnforceRange
}
}
图片Test
中,Test 1
和Test 2
在ListView
中。在这种情况下,Test
元素被突出显示。如何修改视图行为以确保当前(突出显示的)项目始终位于列表的中间?我想要达到的效果如下图所示:
您可以看看 ListView 的 positionViewAtIndex
方法,看看是否有帮助。
您只需要 highlightRangeMode
以及 preferredHighlightBegin
和 preferredHighlightEnd
。来自文档:
These properties affect the position of the current item when the list is scrolled. For example, if the currently selected item should stay in the middle of the list when the view is scrolled, set the preferredHighlightBegin and preferredHighlightEnd values to the top and bottom coordinates of where the middle item would be. If the currentItem is changed programmatically, the list will automatically scroll so that the current item is in the middle of the view. Furthermore, the behavior of the current item index will occur whether or not a highlight exists.
这里是水平 ListView
的完整示例,当前项目位于中心。
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
width: 300
height: 150
visible: true
ListView {
anchors.fill: parent
spacing: 5
model: 20
delegate:
Rectangle {
width: 30
color: ListView.view.currentIndex === index ? "red" : "steelblue"
height: ListView.view.height
Text {
anchors.centerIn: parent
text: index
font.pixelSize: 20
}
}
orientation: Qt.Horizontal
preferredHighlightBegin: 150 - 15
preferredHighlightEnd: 150 + 15
highlightRangeMode: ListView.StrictlyEnforceRange
}
}