Qml:从文件加载组件时将参数作为 URL 的一部分传递

Qml: pass argument as part of URL when loading components from files

是否有一种机制可以在 Qml 中传递 URL 个参数并在以后提取它们?:

StackView.push("Page.qml?#label2);

此致,

您可以 "pass arguments" 从组件创建对象。

StackView.push(component.createObject(null, {"someProperty" : someValue}))

因此您可以使用辅助组件来实现这一点:

Component { id: component; url: "Page.qml" } // or
property Component component: Qt.createComponent("Page.qml") // or
Component { id: component; Page {} }

或者如果你不想用多余的东西污染,你可以直接:

StackView.push(Qt.createComponent("Page.qml").createObject(null, {"someProperty" : someValue}))

最后,将您的 StackView 命名为 StackView 不是一个好主意,我的意思是在 QML 中 属性和 ID 都不能以大写字符开头

无需手动创建对象。就这样做

stackView.push(Qt.resolvedUrl("qrc:/U/R/L/item.qml"), {someCustomProperty: 0})

这是行不通的:

navigationBar.push(Qt.resolvedUrl('qrc:/Pages/BookListPage.qml'), {argument:'test'})

但这行得通(创建一个对象):

navigationBar.push(Qt.createComponent("qrc:/Pages/BookListPage.qml").createObject(null, {argument:'test'}))

实际上根据 QT 文档 ([http://doc.qt.io/qt-5/qml-qtquick-controls-stackview.html][1]),推荐的方法是将至少包含以下最小条目的 属性 列表传递给推送函数 ():

  • item: 这个属性是必填项,存放要推送的item。
  • properties:推送时分配给项目的 QML 属性列表。这些属性将在加载时复制到项目中 时间,或者该项目何时成为当前项目(通常在 推)。

所以我们得到

    navigationBar.push({item: Qt.resolvedUrl("MyRectangle.qml"), properties: {"color" : "red"}});