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

Help with QML code



  • Hi All,
    Hope your'e doing well!
    The following piece of code shows certain actions on the event of key pressed. This code doesn't produce the desired result. Can someone find out the error in it or tell me the reason behind not producing the correct output?

    Thanks in advance!!

    import QtQuick 2.6
    import QtQuick.Window 2.2

    Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Key Handling")

    Item {
        Rectangle{
            x:10;
            y:10
            height: 100; width:100
            radius: 20
            color: "red"
      }
                focus : true
                Keys.onPressed: {
                    if(event.key===Qt.Key_Left)
                     { console.log("move left");
                        event.accepted= true;
                             }
                }
        Keys.onSelectPressed: console.log("Selected");
    
        }
    

    }


  • Moderators

    @Swati777999

    This code doesn't produce the desired result

    please specify this.

    because I do get move left prints on the console



  • @J-Hilk is right. It's printing on the console. However, if you want to move the container by pressing the left key try the following code.

    import QtQuick 2.6
    import QtQuick.Window 2.2
    
    Window {
        width: 640
        height: 480
        visible: true
        title: qsTr("Key Handling")
    
        Item {
            id: mainContainer
            Rectangle{
                x:100;
                y:10
                height: 100; width:100
                radius: 20
                color: "red"
            }
            focus : true
            Keys.onPressed: {
                if(event.key===Qt.Key_Left)
                { console.log("move left");
                    event.accepted= true;
                    mainContainer.x--
                }
            }
            Keys.onSelectPressed: console.log("Selected");
    
        }
    }
    

Log in to reply