anchors of components dynamically created



  • 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);
                    }
                }
    


  • 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!.



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


Log in to reply
 

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