我正在尝试构建一个自定义控件,可以将其他控件(Buttons、Sliders、编辑字段等)组合在一起。
该控件应出现在窗口的右侧,并且应具有固定width的200。这工作正常:
RowLayout {
Item {
Layout.fillWidth: true
}
MyControl {
Layout.fillHeight: true
Layout.preferredWidth: 200
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我在里面使用的布局和控件MyControl。我在其中使用 aRectangle和嵌套的 GroupBoxes (参见下面的代码)。ColumnControlColumnControl
在其中一个GroupBoxes 中,我想Button连续放置几个 s,所以我使用 a RowLayout(我Row也尝试过,结果相同)。Button如果我只连续放置两个或三个s Button,那么 s 就会被拉伸以填充整个宽度,一切都很好。但是当我使用更多Buttons 时,它们不会缩小到一定大小以下。相反,它们RowLayout会向右生长,并且某些Buttons 不可见,因为它们位于窗口之外。
似乎RowLayout首先计算其子级的大小,然后调整自身的大小。现在我想要的是RowLayout固定到父级width,而子级缩小以适合父级。
我设法通过解决方法做到了这一点,但我对此并不满意。一定有更优雅的方式。我还尝试将width的设置RowLayout为 ,parent.width但得到了绑定循环。一切看起来都很好,但我不想编写以几个警告开头的代码。
这是控件的代码:
Rectangle {
id: rootRect
ColumnLayout {
anchors.fill: parent
spacing: 4
GroupBox {
Layout.fillWidth: true
title: "GroupBox Title"
RowLayout {
id: buttonGroupWithWorkaround
enabled: false
anchors.fill: parent
//the workaround:
property int numberOfButtons: 6
property int buttonWidth: (rootRect.width - 2 * buttonGroupWithWorkaround.spacing) / numberOfButtons - buttonGroupWithWorkaround.spacing
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: "|<"
}
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: "<<"
}
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: "<"
}
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: ">"
}
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: ">>"
}
Button {
Layout.preferredWidth: buttonGroupWithWorkaround.buttonWidth
text: ">|"
}
}
}
GroupBox {
Layout.fillWidth: true
title: "NextGroupBox Title"
RowLayout {
id: theButtonGroup
enabled: false
anchors.fill: parent
Button {
//this doesn't work
Layout.fillWidth: true
text: "|<"
}
Button {
Layout.fillWidth: true
text: "<<"
}
Button {
Layout.fillWidth: true
text: "<"
}
Button {
Layout.fillWidth: true
text: ">"
}
Button {
Layout.fillWidth: true
text: ">>"
}
Button {
Layout.fillWidth: true
text: ">|"
}
}
}
GroupBox {
Layout.fillWidth: true
title: "OtherGroupBox Title"
//some other controls
}
}
}
Run Code Online (Sandbox Code Playgroud)
调整尺寸有时可能有点棘手。
fillWidth确保Buttons增大或缩小以填充可用空间。然而,这种行为并不是任意的。它遵循 上设置的其他约束Item。特别是在尺寸下永不implicitWidth缩水Item。
因此,在这种情况下,您可以通过设置较小的 来解决问题implicitWidth,如下所示:
Button {
Layout.fillWidth: true
text: ">"
implicitWidth: 20 // the minimum width will be 20!
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以定义一个自定义ButtonStyle,它定义了一个合适的大小label,但在这种特定情况下,它听起来确实有点过分了。
另请参阅此答案 (或 SO 上的其他资源),以更好地掌握布局/大小调整。