将它们添加到listview时如何保留最后的项目?

问题描述 投票:0回答:1

我有一个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
            }
        }
    }
}

我在listview之外有一个按钮,当点击时它只是:

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

新项目刚刚添加到列表的底部,当超过10时隐藏。当添加项目时,我希望列表自动滚动到它。

qt listview qml scrollview
1个回答
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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.