为什么anchors.fill不能在QML ListView的委托子视图中工作,什么是一个很好的解决方案?

Zso*_*ari 0 qt listview qml qtquick2

我遇到了这个:

ListView {
    id: listView
    model: ["Lorem","Ipsum"]
    delegate: Item {

        height: 20
        Text {
            z: 2
            text: modelData
            anchors.fill: parent
        }

        Rectangle {
            z: 1
            color: "red"
            // this does not work:
            anchors.fill: parent
            // this works, but I have mixed feelings about it:
            // height: 20; width: listView.width
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,显然,anchors不在委托的子项目中工作(在这种情况下,Rectangle根本不显示).我想了解这背后的机制.另外,我想问一下处理这种情况的首选方法是什么?谢谢!

Mit*_*tch 11

Item有一个implicitWidthimplicitHeight零,所以使你RectangleText填充它将导致他们没有大小.

您的代码有两个问题:

  1. ListView没有widthheight指定.
  2. 您的代表没有width指定.

以下是正确执行此操作的一种方法:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 300
    height: 300
    visible: true

    ListView {
        id: listView
        anchors.fill: parent
        model: ["Lorem","Ipsum"]
        delegate: Item {
            width: listView.width
            height: textItem.implicitHeight

            Text {
                id: textItem
                z: 2
                text: modelData
                width: parent.width
            }

            Rectangle {
                z: 1
                color: "red"
                anchors.fill: parent
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

的文档ListView提供了更多信息.