首页 > 解决方案 > 如何在布局中正确嵌套 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 }
          }
        }
      }
    }
}

标签: qtlayoutqml

解决方案


要使突出显示起作用,您需要在 ListView 上设置 currentIndex

delegate: Item {
    height: 50
    width: 180
    Button { 
        text: name 
        onClicked: {
            robotList.currentIndex = index
        }
    }
}

对于列表的宽度,我认为您应该将其锚定到它的父级(并删除height: childrenRect.height):

ListView {
    id: robotList
    anchors.fill: parent
    ...
}

推荐阅读