为什么anchors.fill在QML ListView的委托的子视图中不起作用,什么是不错的解决方案?



我遇到了这个:

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
        }
    }
}

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

ItemimplicitWidthimplicitHeight为零,因此让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
            }
        }
    }
}

ListView的文档有更多的信息

最新更新