如何实现点击TextField外的区域使TextField失去焦点?

bai*_*bai 7 qt qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TextField {
        id:textField
        width: 130
        height: 50
    }

    Button {
        anchors.right: parent.right
        text: "lose Focus"
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么在单击按钮时 textField 不会失去焦点?如何实现点击TextField外的区域使TextField失去焦点?

Mit*_*tch 8

使用现有代码的最简单方法是在单击按钮时强制将焦点集中在另一个项目上:

Button {
    anchors.right: parent.right
    text: "lose Focus"
    onClicked: forceActiveFocus()
}
Run Code Online (Sandbox Code Playgroud)

TextField在单击区域外的区域时失去焦点,您可以执行类似的操作MouseArea

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea {
        anchors.fill: parent
        onClicked: forceActiveFocus()
    }

    TextField {
        id: textField
        width: 130
        height: 50
    }
}
Run Code Online (Sandbox Code Playgroud)

此项目需要低于(即 Z 值低于)场景中的其他项目。您还可以使其成为其他项目的父项以实现此目的:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea {
        anchors.fill: parent
        onClicked: forceActiveFocus()

        TextField {
            id: textField
            width: 130
            height: 50
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Qt Quick Controls 2,则可以使用以下focusPolicy属性,例如Pane

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Pane {
        anchors.fill: parent
        focusPolicy: Qt.ClickFocus
    }

    TextField {
        id: textField
        width: 130
        height: 50
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 尝试在 `ScrollView` 中使用 `TapHandler`:`TapHandler { onTapped: textField.focus = false }`。如果这不起作用,我建议提出一个新问题。 (2认同)