mariomunera
mariomunera

Reputation: 323

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.

Upvotes: 4

Views: 22033

Answers (2)

Nishant Shah
Nishant Shah

Reputation: 1586

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.

Upvotes: 8

JuliusG
JuliusG

Reputation: 2371

You do not have to use the Qt.'something' to change the properties of the QML objects. The way to change the properties is by 'objectId'.'property' = "value";. So try this:

Container {
  objectName: "formContainer"
  id: formContainer

  Label {
    id: labelTest
    text: "test"
  }

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

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

Upvotes: 2

Related Questions