Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically change label text QML

This is the silliest thing to do in any language but I'm stuck on how to do it in QML.

How to change the text value of a Label in QML? What am I missing..

My code is the following:

Container {
  objectName: "formContainer"
  id: formContainer

  property alias text1: labelTest.text

  onCreationCompleted: {
      Qt.labelTest = labelTest;
      Qt.text1 = formContainer.text1;
  }

  Label {
      id: labelTest
      text: "test"
  }

  TextField {
      id: textFieldPass
      onFocusedChanged: {
             if (focused) {
                     Qt.myFunction();
             }
      }
   }

    function myFunction(){
       //Enter successfuly to the function
       console.log("Qt.labelTest.text:" + Qt.labelTest.text);  //Output: undefined
       Qt.labelTest.text = "Y U NO change!";  //Does nothing
       Qt.text1 = "Y U NO change!";           //Does nothing  
    }
 }

I'm not sure why is not working. Even with an alias property the text refuses to change. I will appreciate any help.

Thanks and regards.

like image 902
mariomunera Avatar asked Oct 20 '25 06:10

mariomunera


1 Answers

You need to access alias using the control's id.aliasname. & make myFunction global by declaring it in its root (i.e. Page in this case), if it is being used in multiple slots like this:

Page {
function myFunction() {
    formContainer.text1 = "Y U NO change!";
}
Container {
    id: formContainer
    property alias text1: labelTest.text
    Label {
        id: labelTest
        text: "test"
    }
    TextField {
        id: textFieldPass
        onFocusedChanged: {
            if (focused) {
                myFunction();
            }
        }
     }
  }
}

or if it is being used only for TextField control, you can make it local for it like this:

Page {
Container {
    id: formContainer
    property alias text1: labelTest.text
    Label {
        id: labelTest
        text: "test"
    }
    TextField {
        id: textFieldPass
        onFocusedChanged: {
            if (focused) {
                myFunction();
            }
        }
        function myFunction() {
            formContainer.text1 = "Y U NO change!";
        }
    }
}
}

Hope this helps.

like image 83
Nishant Shah Avatar answered Oct 23 '25 00:10

Nishant Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!