QML 在设置锚点时忽略宽度和高度
QML ignores width and height when setting anchors
我正在尝试了解锚点在 QML (Qt Quick 2.0) 中的工作原理。我有一个像这样的简单项目:
AddButton.qml:
Item {
Button {
text: "ADD"
width: 100
height: 50
}
}
我像这样添加到主 QML 文件中:
main.qml:
Item {
id: root
width: 800
height: 600
AddButton {
id: addButton
}
}
这很好用。但是,一旦我尝试使用锚将按钮放在右下角,按钮就会消失:
main.qml:
Item {
.....
AddButton {
id: addButton
anchors.right: parent.right
anchors.bottom: parent.bottom
}
}
如果我在主 QML 文件级别设置宽度和高度,它只会返回:
main.qml:
Item {
.....
AddButton {
id: addButton
width: 100
height: 50
anchors.right: parent.right
anchors.bottom: parent.bottom
}
}
所以我想知道,为什么当我设置锚点时按钮消失了?有没有什么方法可以让它在不设置主 QML 文件中的宽度和高度的情况下工作(基本上是让它使用 AddButton.qml 中设置的任何大小?)
问题是封装 Item
没有明确的 width
height
。在这种情况下,引擎引用 "natural" witdh/height,即 implicitWidth
/implicitHeight
属性。在大多数情况下,这些属性恰好为零,即使在这种特定情况下也是如此。因此,您的自定义类型具有零维。
因此 AddButton.anchors.bottom
实际上位于封装 Button
的最顶部,后者又突出了封装 Item
这有两点:
除非您想隐藏 Button
的内部结构,否则您不需要用项目封装 Button
。
如果后者是你的愿望,试试这个:
Item {
width: 100 //give the object a dimension!
height: 50
Button {
text: "ADD"
anchors.fill: parent
}
}
现在您可以锚定它,它不会被定位到其他地方。
我正在尝试了解锚点在 QML (Qt Quick 2.0) 中的工作原理。我有一个像这样的简单项目:
AddButton.qml:
Item {
Button {
text: "ADD"
width: 100
height: 50
}
}
我像这样添加到主 QML 文件中:
main.qml:
Item {
id: root
width: 800
height: 600
AddButton {
id: addButton
}
}
这很好用。但是,一旦我尝试使用锚将按钮放在右下角,按钮就会消失:
main.qml:
Item {
.....
AddButton {
id: addButton
anchors.right: parent.right
anchors.bottom: parent.bottom
}
}
如果我在主 QML 文件级别设置宽度和高度,它只会返回:
main.qml:
Item {
.....
AddButton {
id: addButton
width: 100
height: 50
anchors.right: parent.right
anchors.bottom: parent.bottom
}
}
所以我想知道,为什么当我设置锚点时按钮消失了?有没有什么方法可以让它在不设置主 QML 文件中的宽度和高度的情况下工作(基本上是让它使用 AddButton.qml 中设置的任何大小?)
问题是封装 Item
没有明确的 width
height
。在这种情况下,引擎引用 "natural" witdh/height,即 implicitWidth
/implicitHeight
属性。在大多数情况下,这些属性恰好为零,即使在这种特定情况下也是如此。因此,您的自定义类型具有零维。
因此 AddButton.anchors.bottom
实际上位于封装 Button
的最顶部,后者又突出了封装 Item
这有两点:
除非您想隐藏 Button
的内部结构,否则您不需要用项目封装 Button
。
如果后者是你的愿望,试试这个:
Item {
width: 100 //give the object a dimension!
height: 50
Button {
text: "ADD"
anchors.fill: parent
}
}
现在您可以锚定它,它不会被定位到其他地方。