簡體   English   中英

如何以編程方式將 ScrollView 滾動到底部?

[英]How to programatically scroll a ScrollView to the bottom?

我一直在嘗試創建一個使用 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 實現這一點? 如果沒有,是否有人可以替代這種方法?

原因

您正在嘗試將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()
    }
}

結果

該示例產生以下結果:

帶有列表的窗口,滾動到底部

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM