Search code examples
qtqmlqt-quick

How to shift focus from one text box to another in QtQuick?


The code creates two input text boxes:

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

In the output window the focus, by default, is set to the text box A. How should I move the focus to text box B by:
1. Keyboard
2. Mouse

?


Solution

  • So, lots of little things:

    1) When you click with the mouse it should already shift focus; no need to worry about that.

    2) Your layout is difficult in column format, and by default the TextInput had no width which makes it hard to use

    3) the real answer: You can set the focus on an item to switch it (see below)

    4) But you should probably also use the KeyNavigation system too, also seen in the example below, as people are used to using tab/shift-tab for switching between items.

    So, here's some modified example code that does what you want:

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