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"
}
}
why textField don't lose Focus when Button Click? How to achieve click an area outside the TextField to make the TextField lose focus?
To close keyboard / to hide the keyboard you need to simply remove focus from textfield & thus it automatically dismiss the keyboard. So to remove focus from textfield you just need to run FocusScope unfocus, when user tap outside the textfield.
Next, we need to check to see if the current FocusNode has the “primary focus.” If it doesn't, we call unfocus() on the current node to remove focus and trigger the keyboard to dismiss. If you attempt to unfocus() a node that currently has the primary focus, Flutter will throw an exception.
To give focus to a text field as soon as it's visible, use the autofocus property. TextField( autofocus: true, );
The simplest way using your existing code is to force active focus on another item when the button is clicked:
Button {
anchors.right: parent.right
text: "lose Focus"
onClicked: forceActiveFocus()
}
To make the TextField
lose focus when clicking the area outside of it, you can do something similar with 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
}
}
This item needs to be below (i.e have a lower Z value than) other items in the scene. You can also make it a parent of the other items to achieve this:
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
}
}
}
If you're using Qt Quick Controls 2, you can use the focusPolicy
property on e.g. 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With