qt - QML RowLayout 不会根据内容动态调整大小
问题描述
我对 Qt Widgets 有一些经验,但最近才开始使用 QML。
我面临的问题是我希望 QML 中定义的一些布局能够自动调整以适应它们的内容。这有效,但不是动态的,即如果内容更改布局不适应。使用旧式(非 QML)布局/小部件方法,这会自动发生。
这是一个示例(我的代码看起来不同并且由不同的文件组成,但我将这个 MWE 粘贴在一起以演示问题):
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.2
Window {
id: root
visible: true
width: 640
height: 480
property var nbx: 3
Column {
RowLayout {
Repeater {
model: 3
Rectangle {
width: childrenRect.width
height: childrenRect.height
color: "green"
ColumnLayout {
Rectangle {
height: 10
}
RowLayout {
Repeater {
model: root.nbx
Rectangle {
width: 20
height: 20
color: "orange"
}
}
}
}
}
}
}
Button {
text: "5 boxes"
onClicked: root.nbx= 5;
}
Button {
text: "2 boxes"
onClicked: root.nbx = 2;
}
}
}
我怎样才能用 QML 达到同样的效果?
解决方案
您可以通过将green的隐式大小设置为 child的隐式大小来使其工作。我不完全确定为什么,似乎属性没有正确更新。Rectangle
ColumnLayout
childrenRect
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.2
Window {
id: root
visible: true
width: 640
height: 480
property var nbx: 3
ColumnLayout {
RowLayout {
Repeater {
model: 3
Rectangle {
implicitHeight: col1.implicitHeight // <--- here is the change
implicitWidth: col1.implicitWidth
color: "green"
ColumnLayout {
id: col1
Rectangle {
height: 10
}
RowLayout {
Repeater {
model: root.nbx
Rectangle {
width: 20
height: 20
color: "orange"
}
}
}
}
}
}
}
Button {
text: "5 boxes"
onClicked: root.nbx= 5;
}
Button {
text: "2 boxes"
onClicked: root.nbx = 2;
}
}
}
推荐阅读
- c# - 为什么我的 LINQ 查询中不包含来自 AspNetUser 的数据?
- scala - 类型稳定参数多态性
- gradient - NetLogo 中的趋化性
- cassandra - Cassandra 如何翻阅墓碑和活细胞?
- sql - PL/SQL Oracle dbms_output 使输出均匀
- python - Matplotlib:散点图和颜色条颜色不匹配
- swift - SwiftUI Textfield 实际上并未对数据进行更新
- css - How to make a triangle shape with Tailwind?
- python - 保存多张图像
- firebase - Crashlytics 找不到 Google 服务生成的资源文件