QML Out of focus problem

Info Thread
By -
0

 QML Editor - IntelliJ IDEs Plugin | Marketplace

The common weird out-of-focus situation in Qml is that the focus of a certain control is clearly set, but it does not actually take effect. What is the situation? Let's analyze this situation with an example.

1. Common out-of-focus situations

  • snatched by other controls;
  • Mistakenly thought that the setup was successful.

2. About the control being robbed

2.1 First look at the following examples

Dialog {
    id: dialog
    width: 100; height: 100
    onHidden: {
        dialog.forceReset() // restore focus to 'yes' button
    }
}

Rectangle {
    width: 100; height: 200
    color: activeFocus ? "red" : "lightblue"

    MouseArea {
        anchors.fill: parent
        onClicked: {
            parent.forceActiveFocus()
            dialog.hide();
        }
    }
}

2.2 Why does this cause the Rectangle to lose focus?

  • When the button is pressed, the Dialog is dismissed and its original focus state is restored;
  • Because dialog.hide()the dialog regains the focus after the call.

2.3 What should be done in this situation?

  • Make sure that the logic after setting the focus can no longer have other behaviors of setting the focus;
  • Put the focus setting to the last execution;
  • You can use a timer to delay execution to ensure that you are the last to get the focus while other focus is being restored.

3. When the general control gets the focus

3.1 Direct setting to get the focus

  • When onClicked is triggered, call Rectangle's forceActiveFocus, so that it gets the focus;
  • You can also directly set the value of focus to get the focus.
Rectangle {
    width: 100; height: 200
    focus: true
    color: activeFocus ? "red" : "lightblue"

    MouseArea {
        anchors.fill: parent
        onClicked: parent.forceActiveFocus()
    }
}

3.2 Obtain focus indirectly

  • When the FocusScope gets the focus, it gets the focus focus:trueindirectly because the rect is set in advance.
FocusScope {
    id: scope
    width: 100; height: 200
    focus: false

    Rectangle {
        id: rect
        anchors.fill: parent
        focus: true
        color: activeFocus ? "red" : "lightblue"
    }
}
Tags:

Post a Comment

0Comments

Post a Comment (0)