如何替换()Qml StackView 中不在堆栈顶部的项目?

How to replace() an item in Qml StackView that is not on the top of the stack?

根据 the Qt docs 我应该可以调用:

Item replace(target, item, properties, operation)

Replaces one or more items on the stack with the specified item and operation, and optionally applies a set of properties on the item. The item can be an Item, Component, or a url. Returns the item that became current.

所以如果我要制定:

stackView.replace(stackView.get(stackView.depth - 3), mycomponent)

我希望位于 stackView 索引比最大索引小 2 的项目替换为 mycomponent。然而,这种情况并非如此;似乎索引 depth - 1depth - 2 以及 depth - 3 从堆栈中弹出,然后添加了 mycomponent 的实例。如何在不丢失堆叠较高的对象的情况下替换 depth - 3 的索引?

MVP: 在下面的代码中,如果我 pushpushpush,那么 replace,我希望 Depth at onCompleted: 4Current Index: 1 的值.相反,我得到 Depth at onCompleted: 2

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    id: window

    Component {
        id: mycomponent
        Row {
            spacing: 2
            Button {
                text: "Push"
                onClicked: push(mycomponent)
            }
            Button {
                text: "Pop"
                onClicked: pop()
            }
            Button {
                text: "Replace"
                onClicked: stackView.replace(stackView.get(stackView.depth - 3), mycomponent)
            }
            Text {
                text: "Current Index: " + (stackView.depth - 1)
            }
            Text {
                Component.onCompleted: text = "Depth at onCompleted: " + stackView.depth
            }
        }
    }

    StackView {
        id: stackView
        initialItem: mycomponent
    }
}

并不是所描述的行为是正确的documented (second paragraph)

If the target argument is specified, all items down to the item will be replaced. If target is null, all items in the stack will be replaced. If not specified, only the top item will be replaced.

一个解决方案可能是首先弹出 3 个项目(并存储两个最上面的项目),推送您的新组件,最后推送存储的项目:

...
Button {
    text: "Replace"
    onClicked: {
        var item1 = stackView.pop();
        var item2 = stackView.pop();
        stackView.pop();
        stackView.push(mycomponent);
        stackView.push(item2);
        stackView.push(item1);            
    }
}
...