Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML: move to next control in form

Tags:

qt

qml

qtquick2

How can I move focus from one control to next one inside QML form? By default it works with Tab button but I need to change it to Enter. All the control are ordered with Gridlayout with 2 columns.

like image 939
folibis Avatar asked Jul 08 '14 05:07

folibis


3 Answers

I've defined a new component, TextFieldMoveOnReturn.qml

import QtQuick 2.0
import QtQuick.Controls 1.1

TextField {
    Keys.onReturnPressed:  nextItemInFocusChain().forceActiveFocus()
}

If you use this one instead of TextField, you get the required behaviour

edit a better solution: define a new component GridLayoutNextOnReturn.qml

import QtQuick 2.0
import QtQuick.Layouts 1.1

GridLayout {
    Keys.onReturnPressed: {
        for (var i = 0; i < children.length; ++i)
            if (children[i].focus) {
                children[i].nextItemInFocusChain().forceActiveFocus()
                break
            }
    }
}

and use normal TextField inside - works like a charm

like image 143
CapelliC Avatar answered Nov 09 '22 01:11

CapelliC


You can use onEditingFinished:

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1

Rectangle {
    width: 400
    height: 400

    GridLayout {
        anchors.fill: parent
        columns: 2

        Label {
            text: "Name"
        }
        TextField {
            onEditingFinished: addressEdit.focus = true
        }
        Label {
            text: "Address"
        }
        TextField {
            id: addressEdit
        }
    }
}
like image 28
Mitch Avatar answered Nov 09 '22 00:11

Mitch


In order to make it more robust and flexible, you should make same behaviour for Tab and Enter/Return keys.
Handle keyPressed event and use KeyNavigation.tab instead of nextItemInFocusChain to focus next element as follow:

import QtQuick 2.12
import QtQuick.Controls 1.12

Column {
    TextField {
        id: field1
        KeyNavigation.tab: field2
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field2
        KeyNavigation.tab: field3
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
    TextField {
        id: field3
        KeyNavigation.tab: field1
        activeFocusOnTab: true
        Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
    }
}

So you controlled order of focus and users can use both tab and return keys interchangeably which results better UX.
Whenever you want to change order, just change KeyNavigation.tab values :)

Note: I extremely suggest you to avoid using nextItemInFocusChain because of future changes and flexibility

like image 1
S.M.Mousavi Avatar answered Nov 09 '22 02:11

S.M.Mousavi