Search code examples
qtscrollviewqmlqtquick2qtquickcontrols

Editing a TextInput in a ScrollView


I have an issue with my QML. I'd like to edit a TextInput based on an action, setting the focus attribute to true. It works when the TextInput is located in a Rectangle, but not in a ScrollView. Here is an example:

Item {
    id: main
    width: 640
    height: 480

    ScrollView{
        id: scrollView
        height: parent.height/2
        width: parent.width

        Rectangle{
            border.color: "black"
            border.width: 1
            anchors.centerIn: parent
            height: 25
            width: 200
            TextInput{
                id: ti1
                anchors.fill: parent
                verticalAlignment: TextInput.AlignVCenter
                horizontalAlignment: TextInput.AlignHCenter
            }
        }

    }

    Rectangle{
        y: height
        height: parent.height/2
        width: parent.width

        Rectangle{
            border.color: "black"
            border.width: 1
            anchors.centerIn: parent
            height: 25
            width: 200
            TextInput{
                id: ti2
                anchors.fill: parent
                verticalAlignment: TextInput.AlignVCenter
                horizontalAlignment: TextInput.AlignHCenter
            }
        }
    }

    MouseArea{
        anchors.fill: parent
        onClicked: {
            if (mouseY < parent.height/2){
                ti2.focus = false
                ti1.focus = true
            }else{
                ti1.focus = false
                ti2.focus = true
            }
        }
    }

}

When I click on the bottom half of the window, the TextInput ti2 is editable. But when I click on the top half, ti1 is not.

Does anybody have any idea? The behaviour is the same with TextEdit.

Thanks.


Solution

  • I think it is because: "Only one Item can be a direct child of the ScrollView and the child is implicitly anchored to fill the scroll view.".

    From: http://doc.qt.io/qt-5/qml-qtquick-controls-scrollview.html

    Perhaps the tree of components is unavailable in a ScrollView.

    But if you use:

    ti1.forceActiveFocus();
    

    instead of:

    ti1.focus = true
    

    it works.