Problem using mapFromItem()



  • Hi,

    I am trying to constrain a rectangle in one of my QML components to the top of the QML application window. According to the documentation, passing 'null' to mapFromItem(), the scene's root will be used as a mapping reference.

    The component is used as follows:
    @
    ComponentX {
    id: compX
    anchors.verticalCenter: parent.verticalCenter
    }
    @

    However, the mapping statement inside the component is always zero, e.g. here:
    @
    // ComponentX
    Rectangle {
    Rectangle {
    y: mapFromItem(null, 0, 0).y
    }
    }@
    The inner rectangle will thus always be top-aligned to the component itself but not the application window.

    If I use a mouse event however, mapping returns the correct values:
    @
    // ComponentX
    Rectangle {
    Rectangle {
    y: mapFromItem(null, 0, 0).y
    }
    MouseArea {
    onClicked: { console.debug("y: " + mapFromItem(null, 0, 0).y) }
    }
    }@

    Can anyone reproduce this issue or is there a better way to constrain components to the screen?



  • If you're building a component that's used solely for a specific application, then the easiest way is to tag your "topmost" element with an id (the one used to essentially create the window), I usually tag it as "id: app", then just use the anchors to "anchors.verticalCenter: app.verticalCenter", that way it should be constrained to align to the topmost window.



  • The problem is that in this code:

    @
    Rectangle {
    y: mapFromItem(null, 0, 0).y
    }
    @

    mapFromItem() is only called when the y position is initially set - i.e. when the item is created, before all the items in the scene are properly sized and laid out. There is nothing to notify the Rectangle when everything has been sized and the y property should be re-evaluated.

    What you could do is ensure the y is not set until the components are initialized:

    @
    Rectangle {
    Component.onCompleted: y = mapFromItem(null, 10, 10).y
    }
    @

    However the y is not updated if the window is resized. In this case the root item will have to notify the component to update the y (e.g. by adding a method in ComponentX that is called when the root item's height changes).


Log in to reply
 

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