qt - 如何访问包含 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
似乎是我正在寻找的东西,但我不知道如何使用它。我尝试了以下所有方法(替换Button
s' 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
,但不是更好)
解决方案
请注意,此 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.
}
}
}
}
推荐阅读
- grpc - Java Proto 生成找不到源
- python - SQLAlchemy returning
, values etc - javascript - 在反应中将常量转换为自己的文件
- spring - 发布微服务路由到网关
- c# - How to use default serialization in a custom System.Text.Json JsonConverter?
- shopify - Storing and retrieving data for custom Shopify apps
- git - Git push atomically, only if the target branch is at the expected SHA
- flutter - How to increase counter value if i drag up and decrease if i drag down with Gesture Detector?
- discord.js - Unhandled promise rejection: ReferenceError: member is not defined
- python - 触发 .click 动作时触发“TimeoutException”错误