15

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?

Mohsen Zahraee
  • 3,309
  • 5
  • 31
  • 45

1 Answers1

25

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
Mitch
  • 23,716
  • 9
  • 83
  • 122
  • i found my active focused object! now is there any solution to find where focus is changing? – Mohsen Zahraee Dec 24 '17 at 14:17
  • Are you using Qt Quick Controls 2? – Mitch Dec 24 '17 at 14:52
  • Yes i use qtquick controls 2 – Mohsen Zahraee Dec 24 '17 at 15:00
  • This is useful, but it doesn't answer how to have a single line of code find the active window. Instead, it requires the line of code to be propagated throughout all the components. This is a problem if, for instance, you'd like to close a window as a result of a global action. Any thoughts on how to grab an active window from anywhere? – Kenn Sebesta Nov 11 '19 at 11:49
  • @KennSebesta https://doc.qt.io/qt-5/qguiapplication.html#focusWindow is probably the easiest way. I don't think there's a QML API for it. – Mitch Nov 11 '19 at 14:32