以下QML代码:
Window {
id: window
width: 450
height: 700
visible: true
StackView {
id: mainStack
property Item itemTest: Item {
id: itemTest
ColumnLayout {
id: mainLayout
width: mainStack.width
ScrollView {
id: scrollview
Layout.fillWidth: true
Layout.fillHeight: true
clip: true
ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
ColumnLayout{
id: colLayout
anchors.fill: scrollview
}
}
}
}
initialItem: itemTest
anchors.fill: parent
}
}
给出错误 “QML ColumnLayout:无法锚定到不是父项或同级项的项目。”
将
anchors.fill: scrollview
替换为 anchors.fill: parent
会使此消息消失,但 ColumnLayout 似乎不会填充 ScrollView。
鉴于这种行为,我得出的结论是,此 QML 文件中的
scrollView
实际上并不是 colLayout
的父级,这违背了我对 QML 中父子关系工作方式的第一直觉。
有人可以向我解释 QML 中关键字“parent”的确切含义吗?非常感谢。
问题在于控件使用了
contentItem
的概念。虽然 ScrollView 本身是一个 Control,而它本身又是一个 Item,但子项的父级是一个名为 contentItem
的不同 Item。
更多信息在这里:
https://doc.qt.io/qt-5/qml-qtquick-controls2-control.html#contentItem-prop
另请参阅那里的评论:
注意:大多数控件使用内容项的隐式大小来计算控件本身的隐式大小。如果您将内容项替换为自定义项,您还应该考虑为其提供合理的隐式大小(除非它是像 Text 这样的项目,它有自己的隐式大小)。
您不想增大 ColumnLayout 来匹配 contentItem,contentItem 将自动调整大小以适应 ColumnLayout 的隐式大小。
如果您想要获得的效果是将 ColumnLayout 的大小与 ScrollView 的大小相匹配,则使用类似以下内容:
ColumnLayout{
id: colLayout
implicitWidth: scrollview.width
implicitHeight: scrollview.height
height: implicitHeight
width: implicitWidth
}
但既然如此,为什么还要使用 ScrollView 呢?通常,您将允许 ColumnLayout 根据其子级来管理其隐式大小。当 contentItem 最终溢出 ScrollView 时,它就会开始自动滚动。