如何通用地引用上一个/下一个兄弟元素?

tem*_*ame 6 qt qml qt-quick qtquick2

例如,如果我希望锚定到父元素,无论其 id 是什么,我都可以编写anchors.top: parent.bottom. 但是,如果我希望锚定到前一个兄弟姐妹或下一个兄弟姐妹怎么办?只能通过 id 来完成吗,还是有办法通用地说?

mlv*_*ljr 4

我们到了!!

import QtQuick 2.0

Rectangle {
    width: 800; height: 400

    //if item is not parented, -1 is returned
    function itemIndex(item) {
        if (item.parent == null)
            return -1
        var siblings = item.parent.children
        for (var i = 0; i < siblings.length; i++)
            if (siblings[i] == item)
                return i
        return -1 //will never happen
    }
    //returns null, if the item is not parented, or is the first one
    function previousItem(item) {
        if (item.parent == null)
            return null
        var index = itemIndex(item)
        return (index > 0)? item.parent.children[itemIndex(item) - 1]: null
    }
    //returns null, if item is not parented, or is the last one
    function nextItem(item) {
        if (item.parent == null)
            return null

        var index = itemIndex(item)
        var siblings = item.parent.children

        return (index < siblings.length - 1)? siblings[index + 1]: null
    }

    Rectangle {
        width: 200; height: 200
        color: "red"
    }
    Rectangle {
        id: green
        width: 200; height: 200
        color: "green"

        property Item previous: previousItem(green)
        anchors.left: (previous != null)? previous.right: undefined

        property Item next: nextItem(green)
        anchors.right: (next != null)? next.left: undefined
    }
    Rectangle {
        width: 200; height: 200
        anchors.right: parent.right
        color: "blue"
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述