如何一般性地参考prev / next兄弟元素?

时间:2014-09-04 03:49:36

标签: qt qml qtquick2 qt-quick

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

4 个答案:

答案 0 :(得分:3)

我们到了!!

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

enter image description here

答案 1 :(得分:3)

这是我处理这种情况的代码。我通常将它放在顶级.qml文件中,甚至放在共享的JavaScript模块中,以便我可以在任何地方使用它而无需复制和粘贴:

function indexOfChild (item, child) {
    var ret = -1;
    if (item && child && "children" in item) {
        for (var idx = 0; ret < 0 && idx < item.children.length; idx++) {
            if (item.children [idx] === child) {
                ret = idx;
            }
        }
    }
    return ret;
}

function prevSibling (item, child) {
    return (item.children [indexOfChild (item, child) -1] || null);
}

function nextSibling (item, child) {
    return (item.children [indexOfChild (item, child) +1] || null);
}

然后我可以简单地调用这3种方法中的任何一种......

唯一的缺点&#34;是一个必须在参数中提供父...

答案 2 :(得分:2)

目前无法访问某个项目的上一个和下一个兄弟姐妹。您可以看到报告here的建议尚未解决。

答案 3 :(得分:2)

您可以在Layouts

中尝试定位项目,而不是锚定到同级项目
相关问题