I need to get width and height of a Rectangle in Component.OnCompleted
handler but if i print the same i am getting some unknown values, Following is the code:
[EDIT-1] - Added more code.
import QtQuick 2.6
import QtQuick.Controls 2.2
import QtQuick.Window 2.3
ApplicationWindow {
id: appWindow
visible: true
width: 600
height: 400
title: qsTr("test")
flags: Qt.Window | Qt.FramelessWindowHint
Rectangle{
id:rectParent
width:parent.width * 0.75
height: parent.height * 0.70
Rectangle{
id:rectChild
width:parent.width * 0.75
height: parent.height * 0.70
Component.onCompleted: {
console.log("Width=",width) //prints "0" .
}
}
}
}
How To get width, height in onCompleted
?
The
parent
of items, nested directly in the window is not the window, but the window'scontentItem
.Try this instead:
The same applies for your "full code":
You can use
parent
in the second rectangle, because its parent will be the first rectangle, but since the first is nested inside the window, it needs to refer to the window instead of its parent to get property sized.Ok, I'll try to start again:
Your problem is a misconception, what hides behind
parent
.Here you assume,
parent
forsomeRect
isappWindow
, and therefor,parent.width = appWindow.width = 600
. This is wrongThe parent of
someRect
can't beappWindow
, asappWindow
is not of typeItem
. In fact,someRect.parent === appWindow.contentItem
, sowidth: parent.width => width: appWindow.contentItem.width
.The problem is, that the width of the
contentItem
is0
when created, and will reseized toappWindow.width
only after creation.This means, that
someRect.width
is also0
until the width ofappWindow.contentItem
has been resized to600
- which won't happen untilComponent.onCompleted
is executed.The solution is, to shortcut the dependency on a width of
appWindow.contentItem
, as the final value is available from the start, in the propertyappWindow.width
.Let's see another example:
Here, the height will be set right from the start, while the width will change only as soon as
appWindow.contentItem
is being resized. So it is better to follow the way, I used for theheight
.