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

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

How to loose focus when i click outside TextInput in QML

问题

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

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

  1. Column {
  2. anchors.fill: parent
  3. Button {
  4. id: backButton
  5. onClicked: { . . . }
  6. }
  7. Rectangle {
  8. id: myRect
  9. TextInput {
  10. id: inputText
  11. anchors {
  12. fill: parent
  13. }
  14. cursorVisible: false
  15. onAccepted: { // do something}
  16. }
  17. }
  18. ListView {
  19. .
  20. .
  21. }
  22. }
英文:

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.

  1. Column {
  2. anchors.fill: parent
  3. Button {
  4. id: backButton
  5. onClicked: { . . . }
  6. }
  7. Rectangle {
  8. id: myRect
  9. TextInput {
  10. id: inputText
  11. anchors {
  12. fill: parent
  13. }
  14. cursorVisible: false
  15. onAccepted: { // do something}
  16. }
  17. }
  18. ListView {
  19. .
  20. .
  21. }
  22. }

答案1

得分: 1

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

  1. Column {
  2. Button {
  3. }
  4. Rectangle {
  5. TextInput {
  6. }
  7. }
  8. ListView {
  9. id: listView
  10. MouseArea {
  11. anchors.fill: parent
  12. onClicked: listView.forceActiveFocus();
  13. }
  14. }
  15. }
英文:

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:

  1. Column {
  2. Button {
  3. }
  4. Rectangle {
  5. TextInput {
  6. }
  7. }
  8. ListView {
  9. id: listView
  10. MouseArea {
  11. anchors.fill: parent
  12. onClicked: listView.forceActiveFocus();
  13. }
  14. }
  15. }

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:

确定