I have MapView as a main window element and I want it to respond to some keyboard presses. But if I click, for example, on the ManuBar and then on the map, the focus remains on the menu. I could handle mouse clicks to set the focus:
ApplicationWindow {
width: 400
height: 300
visible: true
MapView {
id: mapView
anchors.fill: parent
focus: true
MouseArea {
anchors.fill: parent
onClicked: {
mapView.forceActiveFocus()
}
onLongPress: {
mapView.forceActiveFocus()
}
onDoubleClicked: {
mapView.forceActiveFocus()
}
/* right-click events */
}
}
}
But I don't think it's the optimal way to do this. Can you suggest anything to solve the problem?
Whenever you're forcing focus, it's recommended to schedule it with Qt.callLater(mapView.forceActiveFocus)
instead of immediately with mapView.forceActiveFocus()
to avoid potential UI blocking infinite loops.
As to when to do it, you are going to have to try a few different places.
You can place it on the MapView itself. Whenever it loses focus, it tries to acquire it back. The following approach is short, however, it suffers from being too aggressive making it harder to click on anything but your MapView.
MapView {
id: mapView
anchors.fill: parent
focus: true
onFocusChanged: {
if (!focus) {
Qt.callLater(forceActiveFocus);
}
}
}
You can place it on your Menu and/or MenuBar, e.g. whenever it acquires focus, you can ask for it to give it up.
Menu {
onFocusChanged: {
if (focus) {
Qt.callLater(mapView.forceActiveFocus);
}
}
}
You will need to test the above scenarios to see how they operate - this will not be the final solution but, hopefully, a stepping stone to where you need to be.