Qt 如何访问包含QML StackView的文件?
我是QML的新手,我有一个在StackView上推送的组件。我希望从此组件访问包含它的StackView 下面是一个有效的代码Qt 如何访问包含QML StackView的文件?,qt,qml,Qt,Qml,我是QML的新手,我有一个在StackView上推送的组件。我希望从此组件访问包含它的StackView 下面是一个有效的代码 import QtQuick 2.11 import QtQuick.Controls.2.2 ApplicationWindow { id: window StackView { id: stackView initialItem: test1 anchors.fill: parent }
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()
}
}
}
但是,我希望避免通过其id
访问stackView
似乎是我要找的,但我不知道如何使用它。我尝试了以下所有操作(将按钮
s'一次点击
):
这些都不管用。
我是不是误解了什么?我应该如何使用堆栈视图
编辑:这个问题与我的问题非常接近:
我确实可以使用属性来保留对我的StackView
的引用,但如果可能的话,我仍然希望避免这样做。
公认的答案是root.StackView.view.pop()
是正确的方法。我假设root
是这篇文章中页面的id
,所以我尝试了test1.StackView.view.push(test2)
,但仍然不起作用。(也尝试使用根目录
,但并不更好)
请注意,此Q/A是关于QtQuick.Controls 2.x的
我还认为首先使用附加属性是一种很好的方式,而不是通过添加自己的自定义属性将此功能加倍
问题是,您在错误的位置使用了attached属性-它附加到推送到堆栈视图
上的项
,而不是它的任何子项。因此,要使用附加属性,需要首先指定此项的标识符
在已链接的示例中,这是root
。但它不是组件
-对象的id
。它必须是组件
-对象内容的根节点
你应该有这样的东西:
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.
}
}
}
}
你也看过这个吗:。第一个答案似乎就是你需要的。可能是@eyllanesc的复制品确实可能。。。我没看到。编辑(实际上是删除并重新发布,编辑按钮消失):在问题中添加了注释。myComponentRoot.StackView.view
未定义在这种情况下,请共享一个最小的完整且可验证的示例。在您的问题中,您使用不推荐使用的QtQuick.Controls 1。这个问题是关于现代版本2.XI将有一次我回到文明。
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.
}
}
}
}