Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved anchors of components dynamically created

    QML and Qt Quick
    2
    3
    2523
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • N
      Nitenq last edited by

      Hello !

      I have problems with positioning dynamically created objects. When I try to anchor those objects, I get the error "Cannot anchor to a null item". Here is an example where I try to place a button next to a static Rectangle. Any Idea ?

                  Rectangle{
                      id:myRectangle
                      anchors.centerIn: parent
                      color:"yellow"
                      width: 50
                      height: 50
                  }
      
                  Component {
                          id: tagButtonComponent;
      
                         Button {
                              text: "new tag"
                          }
                  }
      
                  function addNewTag(tagName){
                      var newButton = tagButtonComponent.createObject(tagCloudPanel);
      
                      if (newButton === null) {
                          // Error Handling
                          console.log("Error creating object");
                      }
                      else{
                        // --> this line does not work
                          newButton.anchors.left = myRectangle.anchors.right
                          newButton.anchors.leftMargin = 8
      
                       // save the object in array for later use
                          tagButtons.push(newButton);
                      }
                  }
      
      1 Reply Last reply Reply Quote 0
      • M
        miguelorenes last edited by

        the problem is here:

        newButton.anchors.left = myRectangle.anchors.right;
        

        It should be

        newButton.anchors.left = myRectangle.right;
        

        BTW, don't forget newButton and myRectangle need to have a sibling relationship, in other case you will also get an error like:

        QML Button: Cannot anchor to an item that isn't a parent or sibling.
        

        Cheers!.

        1 Reply Last reply Reply Quote 3
        • N
          Nitenq last edited by

          Thanks for the answer, that was an silly mistake ;)

          1 Reply Last reply Reply Quote 0
          • First post
            Last post