英文:
QtQuick Layouts: Why don't the width and height settings affect anything inside the ColumnLayout?
问题
我一直在使用QtQuick并遇到了一个问题,我无法完全理解。
在下面的示例中,我直接设置了矩形的宽度和高度,期望它填充父元素的高度的10%和完整宽度。但是,矩形的大小为零:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Window")
ColumnLayout {
anchors.fill: parent
Rectangle {
width: parent.width
height: parent.height * 0.1
color: "blue"
}
}
}
但是,当我修改代码以使用Layout.preferredWidth
和Layout.preferredHeight
时,矩形的大小如预期般工作:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Window")
ColumnLayout {
anchors.fill: parent
Rectangle {
Layout.preferredWidth: parent.width
Layout.preferredHeight: parent.height * 0.1
color: "blue"
}
}
}
有人能否解释这种行为?
非常感谢您的帮助!
英文:
I've been working with QtQuick and have encountered an issue I can't quite wrap my head around.
In the example below, I've set the width and height of the Rectangle directly, expecting it to fill 10% of the parent's height and the full width. But, the Rectangle's size is zero
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Window")
ColumnLayout {
anchors.fill: parent
Rectangle {
width: parent.width
height: parent.height * 0.1
color: "blue"
}
}
}
But when I modify the code to use Layout.preferredWidth and Layout.preferredHeight instead, the Rectangle sizes are as expected:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Window")
ColumnLayout {
anchors.fill: parent
Rectangle {
Layout.preferredWidth: parent.width
Layout.preferredHeight: parent.height * 0.1
color: "blue"
}
}
}
Could anyone please explain this behavior?
Thank you in advance for your help!
答案1
得分: 1
在QML中,布局根据组合Layout属性为其子项计算大小。要对QML布局有一个基本的了解,我建议阅读文档:
特别是这个部分会给你答案。
正如你已经发现的那样,在布局内无法定义项目的具体高度和宽度。你必须使用其他手段,比如preferredWidth和preferredHeight。
英文:
Layouts in QML calculates the size of its children based on the propertyies set for them in the compount Layout property. To get an basic idea of QML Layouts I recommend to read the documentation:
Especially this section will give you your answere.
And as you already found out, you can not define the congret height and width for an item inside a layout. You have to use other means like preferredWidth and preferredHeight
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论