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

How to set the focus on mouse click on the rectangle



  • Hello, I am learning some thing over qt qml and here is a small example for youir reference.

    import QtQuick 2.6
    import QtQuick.Window 2.2
    import QtQuick 2.0
    import QtQml 2.2 // or later
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        Rectangle{
            id: rec1
            color: "blue"
            width: 200;height: 200
            anchors.centerIn: parent
            focus: true
            Keys.onPressed: {
                if(event.key === Qt.Key_A){
                   console.log("Key A is pressed");
                   event.accepted = true;
                }
            }
            KeyNavigation.down: rec2
        }
        Rectangle {
            id: rec2
            color: "red"
            width: 100; height: 100
            anchors.centerIn: rec1
            Keys.onPressed: {
                if(event.key === Qt.Key_B){
                   console.log("Key B is pressed");
                   event.accepted = true;
                }
            }
        }
        Keys.onPressed: focus?rec1 :rec2
    }
    
    

    I want to do the same example using mouse click. When mouse is clicked on rec2, then focus should be given to rec2 and "Key B is pressed" is to be printed. How can i solve this?



  • Yes, this is working. Small change has to be done.

    import QtQuick 2.6
    import QtQuick.Window 2.2
    import QtQuick 2.0
    import QtQml 2.2 // or later
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        Rectangle{
            id: rec1
            color: "blue"
            width: 200;height: 200
            anchors.centerIn: parent
            focus: true
            Keys.onPressed: {
                if(event.key === Qt.Key_A){
                   console.log("Key A is pressed");
                   event.accepted = true;
                }
            }
    //        KeyNavigation.down: rec2
            MouseArea{
                anchors.fill: rec1
                onClicked:
                {
                    rec2.forceActiveFocus()
                }
            }
        }
        Rectangle {
            id: rec2
            color: "red"
            width: 100; height: 100
            anchors.left: rec1.right
            anchors.verticalCenter:rec1.verticalCenter
            Keys.onPressed: {
                if(event.key === Qt.Key_B){
                   console.log("Key B is pressed");
                   event.accepted = true;
                }
            }
        }
        Keys.onPressed: focus?rec1 :rec2
    }
    
    

Log in to reply