使用上下键导航子 QML TextEdit 时如何更新 QML ScrollView 导航

How to update QML ScrollView navigation when navigating child QML TextEdit with up and down keys

我在 ScrollView 里面有一个 TextEdit。我如何实现逻辑,以便在用户按下向上或向下箭头键时移动 ScrollView 并将文本移动到 ScrollView 范围之外?

//qml
ScrollView {
    id: palGenTextScrollView
    property int scrollBarWidth: 15
    anchors.fill: parent

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onWheel: {
            if (wheel.modifiers & Qt.ControlModifier){
                if (wheel.angleDelta.y > 0)
                {
                    mainTextEdit.font.pixelSize++
                }
                else
                {
                    mainTextEdit.font.pixelSize--
                }
            }
            else{
                wheel.accepted=false
            }
        }
    }
    TextEdit {
        id: mainTextEdit
        text: fileio.palFileText 
        font.family: "Courier"
        wrapMode: TextEdit.Wrap
        selectByMouse: true
        //when going out of upward bounds: palGenTextScrollView.flickableItem.contentY--
        //when going out of downward bounds: palGenTextScrollView.flickableItem.contentY++
    }
}

您可以在详细说明中使用TextArea which does exactly that for you. If you want to bake your own, take a look at the flickable example in TextEdit的文档。

Note that the TextEdit does not implement scrolling, following the cursor, or other behaviors specific to a look-and-feel. For example, to add flickable scrolling that follows the cursor:

    Flickable {
        id: flick

        width: 300; height: 200;
        contentWidth: edit.paintedWidth
        contentHeight: edit.paintedHeight
        clip: true

        function ensureVisible(r)
        {
            if (contentX >= r.x)
                contentX = r.x;
            else if (contentX+width <= r.x+r.width)
                contentX = r.x+r.width-width;
            if (contentY >= r.y)
                contentY = r.y;
            else if (contentY+height <= r.y+r.height)
                contentY = r.y+r.height-height;
        }

        TextEdit {
            id: edit
            width: flick.width
            height: flick.height
            focus: true
            wrapMode: TextEdit.Wrap
            onCursorRectangleChanged: flick.ensureVisible(cursorRectangle)
        }
    }