Simple javascript [SOLVED]



  • I'm new, so first let me apologise for asking what must seem like a very simple question.

    If I have a qml file like :

    Rectangle {
    width: 200
    height: 200
    color :"blue"
    Text {
    id : whatever
    text: "?"
    color : "white"
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.verticalCenter: parent.verticalCenter
    }
    }

    and then use it in javascript to create a component and when it's ready, create an object, I can reference the rectangle using the object returned. But how, in javascript, do I play with the values in the Text part, eg, the text string itself, text colour, etc.

    I can't find a simple example in the javascript documentation that does this - javascript within the documentation appears to be a second class citizen. But most likely I'm missing something !


  • Moderators

    Hi,

    You can do it in 2 ways:

    1. Declare a property in Rectangle and then bind it to the text property of Text element
      @
      Rectangle {
      property string sampleText
      ...
      Text {
      id : whatever
      text: sampleText
      ...
      }
      }
      @

    And then when you create it, access that property with the returned object.
    @
    var obj = comp.createObject(parent)
    obj.sampleText = "SomeText"
    @

    1. Use the children property
      @
      obj.children[0].text = "SomeText"
      @

    If there are many such items you will need to iterate over them to find the exact one using objectName.



  • Thanks. Perfect answer !


  • Moderators

    You're Welcome :)
    Since you are new here, few things:

    1. No need to apologize. There are no dumb questions :)
    2. Please use code tags "@@" for posting the code part. This makes it easy for everyone to read.
    3. Please post the questions in relevant categories. It's not that you wont get an answer but that is what the categories are made for :)
    4. Append [solved] if your question is answered (and solved ofcourse) by editing the post title.

    Happy Coding..



  • Just to pick up on your point 3, in which category should I have posted ?. I felt that general was the right category.


  • Moderators

    Since the question is related to QtQuick/QML and Javascript, the proper place is Forums > Qt Development > Qt Quick.
    The post has been already moved here now.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.