Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Experimenting with focus



  • Hi guys

    I was thinking if I take 3 rectangles and set focus for all three rectangles true so on keyboard key pressed all three rectangles should capture that event and execute code inside Keys.onPressed. But when I checked by running code only first rectangle is able to capture the key event while others are unable to... I am curious to know what is exactly happening...

    Code:

    import QtQuick 2.9
    import QtQuick.Window 2.2
    
    Window {
        visible: true
        width: 640
        height: 600
        title: qsTr("Hello World")
    
    
        Rectangle
        {   id:one
            width:200
            height:200
            color:"RED"
            focus:true
    
            Keys.onPressed:
                   {
                       if(event.key === Qt.Key_Down)
                       {
                       one.color="yellow"
                       }
    
                   }
    
        }
    
        Rectangle
        {   id:two
            y:300
            width:200
            height:200
            color:"red"
            focus:true
            Keys.onPressed:
                   {
                       if(event.key === Qt.Key_Down)
                       {
                       two.color="yellow"
                       }
    
                   }
        }
    
    
        Rectangle
        {   id:three
            x:300
            width:200
            height:200
            color:"red"
            focus:true
            Keys.onPressed:
                   {
                       if(event.key === Qt.Key_Down)
                       {
                       three.color="yellow"
                       }
    
                   }
        }
    }
    

    output:

    0_1549540479683_0f16016e-4f84-4841-aa92-26609fb2321b-image.png

    How can I change the property of all three at once ?



  • @ashajg hi. the problem is about "focus: true" because of this, the other scopes are unreachable.
    maybe you can try in first "if scope" to make all yellow:

    if(event.key === Qt.Key_Down)
    {
    one.color="yellow"
    two.color="yellow"
    three.color="yellow"

                   }

  • Moderators

    @ashajg
    the issue is not with focus, but with activeFocus.
    Only items that have the active focus will detect the onKey event. I don't think more than 1 Item can have the active focus.

    with setting focus to true, that item will get active focus as soon the the item is loaded. My assumption is, that because the whole scene is loaded at once, only the first item with the focus set to true will get the active focus event.

    but I may be wrong.



  • Thanks @Yunus @J-Hilk


Log in to reply