首页 > 解决方案 > 如何访问包含 QML StackView?

问题描述

我是 QML 的新手,我有一个组件被推送到 StackView 上。我想从这个组件访问包含它的 StackView。

这是一个有效的代码

import QtQuick 2.11
import QtQuick.Controls.2.2

ApplicationWindow {
    id: window

    StackView {
        id: stackView
        initialItem: test1
        anchors.fill: parent
    }
    Component {
        id: test1
        Button {
            text: "Go to test2"
            onClicked: stackView.push(test2)
        }
    }
    Component {
        id: test2
        Button {
            text: "Back to test1"
            onClicked: stackView.pop()
        }
    }
}

但是,我想避免stackView通过其访问id

Stack.view似乎是我正在寻找的东西,但我不知道如何使用它。我尝试了以下所有方法(替换Buttons' onClicked):

Stack.view.push(test2)
view.push(test2)
test1.Stack.view.push(test2)
test1.view.push(test2)

这些都不起作用。我是不是误会了什么?我应该如何使用Stack.view

编辑:这个问题看起来真的很接近我的:Access QML StackView from a control

我确实可以使用属性来保留对 my 的引用StackView,但如果可能的话,我仍然想避免这种情况。接受的答案说这root.StackView.view.pop()是正确的方法。我假设root是来自这篇文章的Page's id,所以我尝试了test1.StackView.view.push(test2),但这仍然不起作用。(也尝试过root,但不是更好)

标签: qtqml

解决方案


请注意,此 Q/A 是关于 QtQuick.Controls 2.x

我也认为首先使用附加属性是一种很好的风格,而不是通过添加自己的自定义属性来加倍这个功能。

问题是,您在错误的地方使用了附加属性 - 它附加到Item被推到StackView而不是其任何子级的那个。所以要使用附加属性,你需要先指定这个Item的标识符。

在已链接的示例中,这是root. 但它不是-objectid的。它必须是-objectComponent内容的根节点。Component

你应该有这样的东西:

Component {
    id: myComponent
    Item { // The Page. To this the attached property will be attached.
        id: myComponentRoot // Use this to identify the root node of the pushed item.
        Item { // Some more layers ...
        ...
            Button { // Here you now want to access it perhaps?
                onClicked: myComponentRoot.StackView.view.pop() // Reference the root node of the component to access it's attached properties.
            }
        }
    }
}

推荐阅读