Important: Please read the Qt Code of Conduct -

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 ?

                    anchors.centerIn: parent
                    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");
                      // --> this line does not work
                        newButton.anchors.left = myRectangle.anchors.right
                        newButton.anchors.leftMargin = 8
                     // save the object in array for later use

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


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

Log in to reply