qt - Flow 底部的额外空间
问题描述
我有这样的 QML 代码:
MyItem.qml:
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Item {
id: root
width: parent.width
height: grid.height
Rectangle {
anchors.fill: root
color: "blue"
z: -1
}
Flow {
id: grid
width: parent.width
spacing: 5
Button {
text: qsTr("Button 1")
}
Button {
text: qsTr("Button 2")
}
Button {
text: qsTr("Button 3")
}
}
}
main.qml:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ColumnLayout {
anchors.fill: parent
Button {
Layout.fillWidth: true
Layout.fillHeight: true
text: "hello"
}
MyItem {
Layout.fillWidth: true
}
}
}
如果 Flow 的宽度足以让所有三个按钮位于同一行(与 RowLayout 一样),则 Flow 底部有一个额外的空白区域(大约 Button.height * 2)。看起来 Flow 高度总是被计算为其所有元素高度的总和。
这种行为背后的逻辑是什么?如何使 Flow 适合其内容高度?
EDIT1:它不是 Flow,但“根”项目的高度错误。
EDIT2: 下载示例应用程序
解决方案
您的代码的问题在于表达式的根元素:
anchors.fill: parent
height: grid.height
正在竞争,在第一个表达式中,您表示根的尺寸将采用窗口的大小,这意味着高度,但在下一个表达式中,您表示高度将不再来自窗口,而是来自网格,这样就会产生不确定的行为。唯一的解决方案是确定根项的宽度是窗口的宽度。
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Item {
id: root
height: grid.height
width: parent.width
Rectangle {
anchors.fill: root
color: "blue"
}
Flow {
id: grid
width: parent.width
spacing: 5
Button {
text: qsTr("Button 1")
}
Button {
text: qsTr("Button 2")
}
Button {
text: qsTr("Button 3")
}
}
}
}
更新:
您似乎不知道它们是如何工作的(阅读https://doc.qt.io/qt-5/qml-qtquick-layouts-layout.html#details),默认情况下采用的高度是隐式高度。
此外,如果您使用布局,则不应在直接受布局影响的项目中设置锚点,在您的情况下,CommandsTab 受布局影响,因此您不应该使用width: parent.width
, 是不必要的。
CommandsTab.qml
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Item {
id: root
implicitHeight: grid.height
Rectangle {
anchors.fill: root
color: "blue"
z: -1
}
Flow {
id: grid
width: parent.width
spacing: 5
Button {
text: qsTr("Button 1")
}
Button {
text: qsTr("Button 2")
}
Button {
text: qsTr("Button 3")
}
}
}
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ColumnLayout {
anchors.fill: parent
Button {
Layout.fillWidth: true
Layout.fillHeight: true
text: "hello"
}
CommandsTab {
Layout.fillWidth: true
}
}
}
推荐阅读
- node.js - 在 npm install webdriverio ./node_modules/.bin/wdio 之后:没有这样的文件或目录
- firebase - NoSuchMethodError:在 null 上调用了方法“[]”。(扑)
- css - 我可以使用文档内 SVG 来屏蔽 div 吗?
- .htaccess - Htaccess - 如果设置了 cookie
- angular - 无法加载 TestbedHarnessEnvironment 或如何单击 MatRadioButton
- msbuild - MSBuild 没有为 ClickOnce 发布依赖项的 dll.config
- websocket - Websocket.run_forever() 到 asyncio.run 循环问题
- javascript - 用 Svelte 制作的冒泡排序算法可视化应用程序给了我一些奇怪的输出
- c# - LsaCallAuthenticationPackage Windows API 的示例/示例,用于在 C# 中获取有关 MSV1_0 的信息
- react-native - 无法对未安装的组件执行 React 状态更新。2021