如何在QtQuick中将焦点从一个文本框转移到另一个文本框?

时间:2013-09-27 10:18:27

标签: qt qml qt-quick

代码创建两个输入文本框:

import QtQuick 1.0

Column 
{
  width: 500
  height: 200

  Text 
  {
    id: userInfoTextA
    focus: false
    text: "Enter a value from 0 to 10:"
  }

  TextInput
  {
    id: userInputA
    focus: true

    anchors.left : userInfoTextA.right
    anchors.leftMargin : 20

    validator: IntValidator { bottom:0; top: 20 }

    Keys.onReturnPressed: 
    {
      console.log (userInputA.text)
    }
  }

  Text 
  {
    id: userInfoTextB
    focus: false
    text: "Enter a value from 10 to 20:"
  }

  TextInput
  {
    id: userInputB
    focus: true

    anchors.left : userInfoTextB.right
    anchors.leftMargin : 20

    validator: IntValidator { bottom:0; top: 20 }

    Keys.onReturnPressed: 
    {
      console.log (userInputB.text)
    }
  }
}

在输出窗口中,默认情况下,焦点设置为文本框A. 如何通过以下方式将焦点移动到文本框B:
1.键盘
2.鼠标

1 个答案:

答案 0 :(得分:1)

所以,很多小事情:

1)当你用鼠标点击它应该已经移动焦点;无需担心。

2)您的布局很难以列格式显示,默认情况下TextInput没有宽度,这使得难以使用

3)真正的答案:你可以将焦点设置在一个项目上进行切换(见下文)

4)但你也应该使用KeyNavigation系统,也可以在下面的例子中看到,因为人们习惯使用tab / shift-tab来切换项目。

所以,这里有一些修改后的示例代码可以满足您的需求:

import QtQuick 1.0

Grid 
{
  width: 500
  height: 200
  columns: 2

  Text 
  {
    id: userInfoTextA
    text: "Enter a value from 0 to 10:"
    width: 200
  }

  TextInput
  {
    id: userInputA
    focus: true
    width: 100

    anchors.left : userInfoTextA.right
    anchors.leftMargin : 20

    validator: IntValidator { bottom:0; top: 20 }

    KeyNavigation.priority: KeyNavigation.BeforeItem
    KeyNavigation.tab: userInputB

    Keys.onReturnPressed: 
    {
      console.log (userInputA.text)
      userInputA.focus = false
      userInputB.focus = true
      event.accepted = true;
    }
  }

  Text 
  {
    id: userInfoTextB
    text: "Enter a value from 10 to 20:"
    width: 200
  }

  TextInput
  {
    id: userInputB
    width: 100

    anchors.left : userInfoTextB.right
    anchors.leftMargin : 20

    validator: IntValidator { bottom:0; top: 20 }

    KeyNavigation.priority: KeyNavigation.BeforeItem
    KeyNavigation.backtab: userInputA

    Keys.onReturnPressed: 
    {
      console.log (userInputB.text)
    }
  }
}
相关问题