qt - 如何在布局中正确嵌套 QML ListView 的尺寸?
问题描述
我正在尝试制作一个简单的 QML 布局,左侧是列表,右侧是内容窗格和列表。列表可以具有固定宽度,并且内容窗格应填满剩余空间。(有人记得 CSS 圣杯吗?)
我想出了以下内容,但我一直遇到很多问题,我觉得我完全错误地接近它,违背了在 QML 中做事的“正确”方式。
最初我在使列表占据整个高度时遇到问题,我最终解决了这个问题height: childrenRect.height
,所有其他解决方案都导致了绑定循环。
接下来我开始研究允许用户选择项目,这就是真正的麻烦开始的地方。经过长时间的斗争,我发现它不起作用,因为我的物品宽度为零。但是我一生都无法弄清楚如何使列表与其子级一样宽,或者子级与列表一样宽。
另一个问题是焦点无法正常工作。高亮显示正常(尽管硬编码宽度略有错误),但我无法更改它。没有多少点击或按键将突出显示移动到另一个项目。
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.3
ApplicationWindow
{
visible: true
width: 800
height: 600
title: qsTr("example")
RowLayout {
anchors.fill: parent
anchors.margins: 10
spacing: 10
GroupBox {
title: "List1"
Layout.preferredWidth: 100
Layout.fillHeight: true
ListView {
height: childrenRect.height
model: ListModel {
ListElement { name: "Bill Smith" }
ListElement { name: "John Brown" }
ListElement { name: "Sam Wise" }
}
delegate: Item {
height: 50
Text { text: name }
}
}
}
TabView {
Layout.fillHeight: true
Layout.fillWidth: true
Tab {
title: "Red"
Rectangle { color: "red" }
}
Tab {
title: "Blue"
Rectangle { color: "blue" }
}
Tab {
title: "Green"
Rectangle { color: "green" }
}
}
GroupBox {
title: "List2"
Layout.minimumWidth: 100
Layout.fillHeight: true
ListView {
id: robotList
height: childrenRect.height
focus: true
highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
model: ListModel {
ListElement { name: "Foo" }
ListElement { name: "Bar" }
ListElement { name: "Baz" }
}
delegate: Item {
height: 50
width: 180
Text { text: name }
}
}
}
}
}
解决方案
要使突出显示起作用,您需要在 ListView 上设置 currentIndex
delegate: Item {
height: 50
width: 180
Button {
text: name
onClicked: {
robotList.currentIndex = index
}
}
}
对于列表的宽度,我认为您应该将其锚定到它的父级(并删除height: childrenRect.height
):
ListView {
id: robotList
anchors.fill: parent
...
}
推荐阅读
- javascript - ReferenceError: Array is not defined Javascript
- javascript - 如何在 vuex 的 return 语句中编写 async/await
- c# - How to store C# SpecialFolder path into SQLite database?
- python - How to loop though user objects in django
- angular - Angular 在 ng build --prod 上无法识别来自键值管道的项目
- c# - How to make the placehoder in Generics generic
- python - Extract the largest number from a dataframe column containing strings
- python - 如何将参数传递给pytest测试?
- mysql - 使用mysql计算在同一列中贷记和借记的每种货币的余额?
- swift4.2 - 不支持从 UIView 或子类的后台线程执行任何操作,并且可能导致意外和隐蔽行为