danba
danba

Reputation: 877

Check if a descendant has activeFocus == true in QML

Inside a deeply nested QML GUI, is there an easy way to find out if any child or grandchild etc of an Item has activeFocus == true ?

Item {
  id: intermediateItem
  visible: anyDescendantHasActiveFocus(intermediateItem) ? true : false
  Item {
    Item {
      Item {
        id: hasActiveFocus
        Component.onCompleted: hasActiveFocus.forceActiveFocus()
      }
    }
  }
}

Upvotes: 0

Views: 608

Answers (1)

GrecKo
GrecKo

Reputation: 7150

Instead of drilling down the hierarchy from your base ancestor, you can go up from the current activeFocusItem:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    function anyDescendantHasActiveFocus(ancestor) {
        let item = ancestor.Window.activeFocusItem;
        while (item) {
            if (item === ancestor)
                return true;
            item = item.parent;
        }
        return false;
    }

    Row {
        anchors.centerIn: parent
        spacing: 10
        Repeater {
            model: 3
            Rectangle {
                width: 200
                height: 100
                border.width: 1
                border.color: anyDescendantHasActiveFocus(this) ? "red" : "black"
                Rectangle {
                    anchors.fill: parent; anchors.margins: 10
                    border.width: 1
                    Rectangle {
                        anchors.fill: parent; anchors.margins: 10
                        border.width: 1
                        Rectangle {
                            anchors.fill: parent; anchors.margins: 10
                            border.width: 1
                            Button {
                                anchors.centerIn: parent
                                text: "Focus me"
                            }
                        }
                    }
                }
            }
        }
    }
}

Upvotes: 1

Related Questions