首页 > 解决方案 > QML ListView 锚,边距 = 0 超出父填充?

问题描述

我想知道为什么这会将Icon组件绘制到Item填充之外?使用 Qt 5.5.1

import QtQuick 2.5

Item {
    id: root

    // width: 960    // Actually set in the higher level view
    // height: 540   // Actually set in the higher level view

    ListModel {
        id: items
        ListElement { icon: 'a.png', label: 'Example', x: 0, y: 0 }
        ListElement { icon: 'b.png', label: 'Something', x: 100, y: 0 }
        ListElememt { icon: 'c.png', label: 'Testing', x: 200, y: 50 }
    }

    ListView {
        model: items
        delegate: Icon {
            text: model.label
            iconSrc: model.icon
            anchors {
                top: parent.top
                left: parent.left
                leftMargin: model.x
                topMargin: model.y
            }
        }
        anchors {
            top: parent.top
            left: parent.left
        }
    }

}

前两个图标(y = 0)在更高级别的视图中时将出现在包含之外约 15 像素处。Item

如果我按照以下方式进行操作(没有 ListView),它们会出现在正确的位置(y = 0),即。Item当在更高级别的视图中使用时,它们将位于容器内部。

import QtQuick 2.5

Item {
    id: root

    // width: 960    // Actually set in the higher level view
    // height: 540  // Actually set in the higher level view

    Icon {
        text: 'Example'
        iconSrc: 'a.png'
        anchors {
            top: parent.top
            left: parent.left
            leftMargin: 0
            topMargin: 0
        }
    }

    Icon {
        text: 'Something'
        iconSrc: 'b.png'
        anchors {
            top: parent.top
            left: parent.left
            leftMargin: 100
            topMargin: 0
        }
    }

    Icon {
        text: 'Testing'
        iconSrc: 'c.png'
        anchors {
            top: parent.top
            left: parent.left
            leftMargin: 200
            topMargin: 50
        }
    }
}

为什么Icon在 ListView 中生成的组件与直接定义相比,在使用相同的“X,Y”值时呈现在不同的位置?

标签: qtqmlqt5.5

解决方案


ListView 的目标是将一组项目显示为列表,因此由于几何由 ListView 处理,因此无法建立锚点,而是必须使用中继器:

import QtQuick 2.5

Item {
    id: root

    // width: 960    // Actually set in the higher level view
    // height: 540   // Actually set in the higher level view

    ListModel{
        id: items
        ListElement { icon: 'a.png'; label: 'Example'; x: 0; y: 0 }
        ListElement { icon: 'b.png'; label: 'Something'; x: 100; y: 0 }
        ListElement { icon: 'c.png'; label: 'Testing'; x: 200; y: 50 }
    }

    Repeater {
        model: items
        delegate: Icon {
            text: model.label
            source: model.icon
            anchors {
                top: parent.top
                left: parent.left
                leftMargin: model.x
                topMargin: model.y
            }
        }
    }
}

推荐阅读