记住QML元素中的滚动位置

use*_*525 6 javascript qt scroll qml

我有一些qml充当应用程序的输出(有点像只读控制台).然而,使用它很烦人,因为它打印信息时会滚动回顶部.

例如,假设我TextArea每隔一秒打印一行,大约一分钟后,我会有足够的行,我现在有一个滚动条.我滚动到底部,一秒钟之后,打印出一行文本,使其滚动回到顶部.

我想要的功能是自动滚动到底部(就像控制台打印出来的时候一样),除非用户通过向上滚动覆盖它,然后文本应保持不变.我希望这是有道理的,这里有一些代码:

        ScrollArea {
            id: helpTextScrollArea
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: myButton.bottom
            anchors.topMargin: 5
            anchors.bottom: parent.bottom
            visible: false
            horizontalScrollBar.visible: false

            onVisibleChanged: {
                helpText.visible = visible
            }

            HelpTextArea {
                id: helpText
                width: parent.parent.width - helpTextScrollArea.verticalScrollBar.width
                text: "Oops, no documentation."

                onVisibleChanged: {
                    if(helpTextScrollArea.visible != visible) {
                        helpTextScrollArea.visible = visible
                    }
                }
            }
        }

        Flickable
        {
            id: flick

            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: runStopButton.bottom
            anchors.bottom: parent.bottom
            anchors.topMargin: 5


            TextArea{

                id: messageArea
                anchors.fill: parent

                focus: true

                readOnly: true

                visible: !helpTextScrollArea.visible

                wrapMode: TextEdit.Wrap

                function addText(newText) {
                    text += newText + "\n"
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

注意:我认为我的Flickable没有做任何事情,这是我尝试修复问题的一部分.另外,我使用该功能addText打印到文本区域.我对qml几乎一无所知,大部分代码都是由其他人编写的,我正在尝试使用它.谢谢!

ser*_*rgk 3

您可以将contentY的 属性绑定Flickable到将计算正确位置的表达式。

Flickable {
    id: flick
    states: State {
        name: "autoscroll"
        PropertyChanges {
            target: flick
            contentY: messageArea.height - height
        }
    }
    onMovementEnded: {
        if (contentY === messageArea.height - height) {
            state = "autoscroll"
        }
        else {
            state = ""  // default state
        }
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)