【问题标题】:How to replace() an item in Qml StackView that is not on the top of the stack?如何替换()Qml StackView中不在堆栈顶部的项目?
【发布时间】:2020-02-18 16:41:27
【问题描述】:

根据the Qt docs我应该可以打电话了:

项目替换(目标、项目、属性、操作)

用指定的项目替换堆栈上的一个或多个项目,并且 操作,并且可以选择在项目上应用一组属性。这 item 可以是 Item、Component 或 url。返回成为的项目 当前。

所以如果我要制定:

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

我希望位于 stackView 索引小于最大索引 2 处的项目替换为 mycomponent。然而,这种情况并非如此;似乎索引depth - 1depth - 2depth - 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
    }
}

【问题讨论】:

    标签: qt qml stackview


    【解决方案1】:

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

    如果指定了目标参数,则该项目之前的所有项目都将被替换。如果 target 为 null,则堆栈中的所有项目都将被替换。如果未指定,则仅替换顶部的项目。

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

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

    【讨论】:

    • 感谢您的关注。可惜没有内置的方法来做到这一点,但我只需要足够
    • @TylerM 您想要的操作不是堆栈(视图)行为。您想修改一个非顶层项目,因为它们代表前一帧(通常可以使用后退函数访问),这有点奇怪。请注意,您可以根据需要使用自定义替换功能扩展 StackView
    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多