Search code examples
qmlqtquickcontrols2

Qt Quick Controls 2 TextArea `tabChangesFocus`, how to use Tab key to change focus, not type Tab character


QML TextArea from Qt Quick Controls 1.x (http://doc.qt.io/qt-5/qml-qtquick-controls-textarea.html) had a property called tabChangesFocus, which could be set to toggle the behaviour of the Tab key between two possible actions:

  • true: enter Tab character in the TextArea
  • false: move the focus to next item in the tab Chain

This property doesn't seem to exist for TextArea in Quick Controls 2.x (https://doc.qt.io/qt-5/qml-qtquick-controls2-textarea.html).

The default is the true behaviour, but I would like the false behaviour (focus change).

Does anyone know a simple way to achieve the same effect for Quick Controls 2?


Solution

  • Another way is to use Item::nextItemInFocusChain(). This way, you don't need to know the next item in focus chain:

    import QtQuick 2.9
    import QtQuick.Controls 2.2
    
    ApplicationWindow {
        id: window
        width: 300
        height: 300
        visible: true
    
        Column {
            spacing: 20
    
            TextArea {
                id: textArea1
                focus: true
                text: "TextArea1"
    
                Keys.onTabPressed: nextItemInFocusChain().forceActiveFocus(Qt.TabFocusReason)
            }
    
            TextArea {
                id: textArea2
                text: "TextArea2"
                objectName: text
    
                Keys.onTabPressed: nextItemInFocusChain().forceActiveFocus(Qt.TabFocusReason)
            }
        }
    }