Luca
Luca

Reputation: 11006

Unable to set the parent of a dynamically created QML component

I am creating dynamic component in QML as follows:

var component = Qt.createComponent("PlayerWindow.qml")
if (component.status != component.errorString())
    console.log(component.errorString())
var playerWin = component.createObject(rootWindow);

Here rootWindow is my main application window. Now, the PlayerWindow is quite simple as:

Window {
    id: playerWindow
    width: parent.width
    height: parent.height

    Component.onCompleted: {
        console.log(parent.width)
        console.log(rootWindow.height)
    }
}

The thing is that the values for parent.width and rootWindow.width are really different and this is also evident when the window is displayed. However, rootWindow is set as the parent in the createObject call. So, I am not sure what is happening there but I wanted to know if this is the correct way to set the component parent when they are being dynamically created.

Upvotes: 0

Views: 1057

Answers (1)

folibis
folibis

Reputation: 12874

Try to add console.log(parent) in the code. You will see something like qml: QQuickRootItem(0x1e3e4e0). If you check the Qt doc you will find that Item.parent() returns Item but Windows is not Itemdescendant but QQuickWindow. Also from documentation:

A QQuickWindow always has a single invisible root item ...

So, in your case parent and rootWindow are different objects.

P.S. The dynamic object creation in your code can produce an error since component.createObject will be executed although Qt.createComponent returns error. Just copy the code from Qt documentation.

Upvotes: 1

Related Questions