qtqmlfocusqtquickcontrols2

What Object has Active Focus in QML?


I have a complex GUI with QML but in some situations, I lose my focus and don't know what object has active focus.

Are there any tools or ways to search in QML files and find focused object?


Solution

  • I use this line to see which item has active focus:

    Window {
        onActiveFocusItemChanged: print("activeFocusItem", activeFocusItem)
    }
    

    This code responds to changes in the activeFocusItem property of Window by printing out the item with active focus. ApplicationWindow from Qt Quick Controls 1 and 2 have the same property since they derive from Window.


    To find out how an item got focus, you can set the QT_LOGGING_RULES environment variable to qt.quick.focus = true. This enables logging for Qt's internal focus handling. The output can be a bit tricky to follow though..

    Since you're using Qt Quick Controls 2, it's worth noting that each control has a focusPolicy property which determines how the control gets focus. The default for controls like Button is Qt.StrongFocus, which means that buttons get focus after being clicked or tabbed into. If you're seeing that a control has focus and you don't want it to, just set its focusPolicy to Qt.NoFocus:

    focusPolicy: Qt.NoFocus