如何通过编程将ScrollView滚动到底部?

3

我一直在尝试创建一个函数,使用Qt Quick Controls 2编程方式滚动到底部ScrollView。 我尝试了各种选项,但我发现网上很多支持都是针对Qt Quick Controls 1而不是2。这是我尝试过的:

import QtQuick 2.8
import QtQuick.Controls 2.4

ScrollView {
    id: chatView

    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: inputTextAreaContainer.top

    function scrollToBottom() {
        // Try #1
//      chatView.contentItem.contentY = chatBox.height - chatView.contentItem.height
//      console.log(chatView.contentItem.contentY)

        // Try #2
//      flickableItem.contentY = flickableItem.contentHeight / 2 - height / 2
//      flickableItem.contentX = flickableItem.contentWidth / 2 - width / 2

        // Try #3
        chatView.ScrollBar.position = 0.0 // Tried also with 1.0
    }

    TextArea {
        id: chatBox
        anchors.fill: parent
        textFormat: TextArea.RichText
        onTextChanged: {
            // Here I need to scroll
            chatView.scrollToBottom()
        }
    }
}

有人知道如何使用Qt Quick Controls 2实现这个吗?如果不行,有什么其他方法可以实现吗?

1个回答

5

原因

您正在尝试将 ScrollBar 的位置设置为 1.0

chatView.ScrollBar.position = 0.0 // Tried also with 1.0

然而,您需要考虑到它的大小。

解决方案

在设置滚动条位置时,请考虑 ScrollBar 的大小,像这样:

chatView.ScrollBar.vertical.position = 1.0 - chatView.ScrollBar.vertical.size

我是如何想出这个解决方案的?

我好奇Qt本身是如何解决这个问题的,所以我查看了QQuickScrollBar::increase()函数的实现,并发现了这行代码:

setPosition(qMin<qreal>(1.0 - d->size, d->position + step));

然后我拿了qMin的第一个参数,即1.0 - d->size,问题就很清楚了。

示例

由于您没有提供MCE,所以我自己写了一个。我希望您可以为您的特定情况进行适应。这是代码:

import QtQuick 2.8
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.12

ApplicationWindow {
    width: 480
    height: 640
    visible: true
    title: qsTr("Scroll To Bottom")

    ColumnLayout {
        anchors.fill: parent

        ScrollView {
            id: scrollView

            Layout.fillWidth: true
            Layout.fillHeight: true

            function scrollToBottom() {
                ScrollBar.vertical.position = 1.0 - ScrollBar.vertical.size
            }

            contentWidth: children.implicitWidth
            contentHeight: children.implicitHeight
            ScrollBar.vertical.policy: ScrollBar.AlwaysOn
            clip: true

            ColumnLayout {

                Layout.fillWidth: true
                Layout.fillHeight: true

                Repeater {
                    model: 50

                    Label {
                        text: "Message: " + index
                    }
                }
            }
        }

        TextField {
            Layout.fillWidth: true
        }
    }

    Component.onCompleted: {
        scrollView.scrollToBottom()
    }
}

结果

以下是示例的结果:

窗口显示一个列表,向下滚动


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接