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

State is not getting executed in the QML program?



  • Hello Everyone,
    I am new to Qt and started learning QML, I am trying to do a simple thing.
    Whenever the mouse is placed over the rectangle, color change to green and then back to red. The code is as below.

    import QtQuick 2.9
    import QtQuick.Window 2.2
    Window {
        visible: true
        width: 400
        height: 400
        title: qsTr("Behavior with State Demo")
        Rectangle {
             id: rect
             width: 200
             height: 200
             anchors.centerIn: parent
             // color: "red"
    
    //         Behavior on color {
    //             ColorAnimation {}
    //         }
    
             MouseArea {
                 id: mouser
                 anchors.fill: parent
                 hoverEnabled: true
             }
    
             states: [
                 State {
                     name: "GreenState"
                     when: mouser.containsMouse
                     PropertyChanges {
                         target: rect
                         color: "green"
                     }
                 },
                 State {
                     name: "RedState"
                     when: !mouse.containsMouse
                     PropertyChanges {
                         target: rect
                         color: "red"
                     }
                 }
             ]
             onColorChanged: console.log("Color Changed " + color )
        }
    }
    
    

    The console logs are as below.

    qml: Color Changed #008000
    qml: Color Changed #ffffff
    qml: Color Changed #008000
    qml: Color Changed #ffffff
    qml: Color Changed #008000
    qml: Color Changed #ffffff
    

    So the problem is that "RedState" is not getting executed.
    Can anyone please help me, what is the problem in the above program.


  • Qt Champions 2017

    @xpress_embedo said in State is not getting executed in the QML program?:

    when: !mouse.containsMouse

    Copy & Paste the following line in "RedState". It works.

    when: !mouser.containsMouse



  • As @dheerendra pointed out, you made a typo. It should be mouser instead of mouse in RedState.



  • Thanks @dheerendra , a silly mistake done by me.
    Instead of using mouser I used mouse, and unable to identify this mistake.
    Thanks for solution.


Log in to reply