好吧,我会尝试再次启动:
你的问题是一个误解,什么隐藏背后parent
。
import QtQuick 2.6
import QtQuick.Controls 2.0
ApplicationWindow {
id: appWindow
width: 600
height: 400
visible: true
Rectangle {
id: someRect
width: parent.width * 0.7
heigth: parent.height * 0.7
}
}
在这里,你承担,parent
为someRect
为appWindow
,为此和,parent.width = appWindow.width = 600
。 这是错误
的someRect
父不能appWindow
,为appWindow
是Item
类型的不行。其实someRect.parent === appWindow.contentItem
,所以width: parent.width => width: appWindow.contentItem.width
。
问题是,创建时contentItem
的宽度为0
,并且只有在创建后才会重新设置为appWindow.width
。
这意味着,someRect.width
也是0
直到appWindow.contentItem
宽度已被调整到600
- 直到执行Component.onCompleted
这将不会发生。
的解决方案是,到快捷依赖上的appWindow.contentItem
的宽度,作为最终的值可从一开始,在属性appWindow.width
。
让我们来看看另一个例子:
import QtQuick 2.6
import QtQuick.Controls 2.0
ApplicationWindow {
id: appWindow
width: 600
height: 400
visible: true
Rectangle {
id: someRect
width: parent.width * 0.7 // depends on appWindow.contentItem.width -> initally 0, changing soon after
heigth: appWindow.height * 0.7 // depends on appWindow.height -> initially 400.
Component.onCompleted: console.log('someRect:', width, height) // prints: "someRect: 0 280"
Rectangle {
id: someOtherRect
width: parent.width * 0.7 // depends on someRect.width which is initally 0 as it depends on appWindow.contentItem.width
height: parent.height * 0.7 // depends on someRect.height which is initally 400 * 0.7
Component.onCompleted: console.log('someOtherRect:', width, height) // prints "someOtherRect: 0, 196"
}
}
}
这里,高度会从一开始就被设定,而宽度只有尽快appWindow.contentItem
正在调整改变。所以最好遵循这个方法,我用于height
。
有很多QML组件,其中父可能不是,看起来像什么。对于例如自定义组件所有使用default property alias
将“children”推入嵌套Item
的组件。
为什么在'Component.onCompleted'中需要它?你不能在'onWidthChanged'中做到吗? – GrecKo
比你再次调整大小时会得到它。 – derM
您可以决定保留第一个非零宽度。或者也许需要重新调整大小。我问,为什么pra7需要使用非声明性代码。 – GrecKo