当我在QML中点击TextInput之外的区域时,如何失去焦点?

huangapple go评论96阅读模式
英文:

How to loose focus when i click outside TextInput in QML

问题

我在Column中有三个元素,即ButtonRectangleListViewTextInputRectangle的子元素。当在ListView中选择/点击任何项目时,光标仍然可见在TextInput中。我希望只有在编辑TextInput时才能使用光标,其他情况下不可见。

为了简单起见,我删除了不必要的代码。

Column {
    anchors.fill: parent

    Button {
        id: backButton
        onClicked: { . . . }       
    }

    Rectangle {
        id: myRect

        TextInput  {
            id: inputText
            anchors {
                fill: parent
            }
            cursorVisible: false
            onAccepted: { // do something}
        }
    }

    ListView {
        .
        .
    }
}
英文:

I have three elements inside Column i.e. Button, Rectangle and ListView. TextInput is the child of Rectangle. When select/click on any item in ListView, the cursor is still visible in TextInput. I want the cursor to be available ONLY when i'm editing the TextInput and not otherwise.

For simplicity sake, i have removed unnecessary code.

Column {
    anchors.fill: parent

    Button {
        id: backButton
        onClicked: { . . . }       
    }

    Rectangle {
        id: myRect

        TextInput  {
            id: inputText
            anchors {
                fill: parent
            }
            cursorVisible: false
            onAccepted: { // do something}
        }
    }

    ListView {
        .
        .
    }
}

答案1

得分: 1

你可以在某个地方放置一个MouseArea来捕捉外部的鼠标点击事件,并将焦点从TextInput移开。类似下面的代码应该可以工作:

Column {
    Button {
    }

    Rectangle {
        TextInput  {
        }
    }

    ListView {
        id: listView
        MouseArea {
            anchors.fill: parent
            onClicked: listView.forceActiveFocus();
        }
    }
}
英文:

You can simply put a MouseArea somewhere to catch the outside mouse clicks and move the focus away from the TextInput. Something like this should work:

Column {
    Button {
    }

    Rectangle {
        TextInput  {
        }
    }

    ListView {
        id: listView
        MouseArea {
            anchors.fill: parent
            onClicked: listView.forceActiveFocus();
        }
    }
}

huangapple
  • 本文由 发表于 2023年8月9日 17:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定