Как переключить фокус с одного текстового поля на другое в QtQuick?

Код создает два текстовых поля ввода:

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. Мышь
< бр> ?


person Aquarius_Girl    schedule 27.09.2013    source источник


Ответы (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)
    }
  }
}
person Wes Hardaker    schedule 27.09.2013
comment
Вы сказали: When you click with the mouse it should already shift focus; no need to worry about that. На самом деле я не вижу там текстовое поле (с моим кодом), поэтому я не знаю, где щелкнуть. - person Aquarius_Girl; 30.09.2013