如何实现点击Textfield外的区域,使TextField失去焦点? [英] How to achieve click an area outside the TextField to make the TextField lose focus?

查看:0
本文介绍了如何实现点击Textfield外的区域,使TextField失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"
    }
}

为什么单击按钮时文本字段不会失去焦点? 如何实现点击文本字段外的区域,使文本字段失去焦点?

推荐答案

使用现有代码的最简单方法是在单击按钮时在另一项上force active focus

Button {
    anchors.right: parent.right
    text: "lose Focus"
    onClicked: forceActiveFocus()
}

要使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
    }
}

此项目需要低于场景中的其他项目(即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
        }
    }
}

如果您使用的是Qt快速控件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
    }
}

这篇关于如何实现点击Textfield外的区域,使TextField失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆