将最后一项添加到列表视图时如何查看?

时间:2019-04-03 15:28:07

标签: qt listview qml scrollview

我有一个ListView,可以在其中动态添加ListElements。 ListView最多可以显示10个项目,因此我也有一个ScrollBar。当我添加第11个项目时,我总是希望它滚动到视图中。

ListView {
    id: logListView
    delegate: logListViewDelegate
    model: logListModel

    anchors.fill: parent

    ScrollBar.vertical: ScrollBar {}
}

ListModel {
    id: logListModel
}

Component {
    id: logListViewDelegate
    Item {
        height: 44
        width: logListView.width

        Text {
            id: countText
            width: 18
            font {
                pixelSize: 16
                family: variables.globalFont
            }
            color: colors.foregroundColor3
            text: index+1

            anchors {
                left: parent.left
                leftMargin: 7
                verticalCenter: parent.verticalCenter
            }
        }
        Text {
            id: timeText
            width: 96
            horizontalAlignment: Text.AlignRight
            font {
                pixelSize: 24
                family: variables.globalFont
            }
            color: colors.foregroundColor1
            text: time

            anchors {
                left: countText.right
                verticalCenter: parent.verticalCenter
            }
        }

        Text {
            id: unitText
            width: 18
            font {
                pixelSize: 16
                family: variables.globalFont
            }
            color: colors.foregroundColor3
            text: unit

            anchors {
                left: timeText.right
                leftMargin: 6
                bottom: timeText.bottom
                bottomMargin: 2
            }
        }
    }
}

我在列表视图之外有一个按钮,当单击该按钮时,它确实会:

logListModel.append({
 time: myTime, unit: myUnit
})

新项目将被添加到列表的底部,并在超过10个时被隐藏。添加项目时,我希望列表自动滚动到它。

1 个答案:

答案 0 :(得分:1)

在您的ListView中,通过在调用onCountChanged时(更改模型时)更改currentIndex来滚动到底部:

ListView {
  id: logListView
  delegate: logListViewDelegate
  model: logListModel

  anchors.fill: parent

  ScrollBar.vertical: ScrollBar {}

  onCountChanged: {
    var newIndex = count - 1 // last index
    positionViewAtEnd()
    currentIndex = newIndex
  }
}