【问题标题】:In QML, could a component property be the component itself?在 QML 中,组件属性可以是组件本身吗?
【发布时间】:2023-01-17 19:21:37
【问题描述】:

我试图将一个组件本身分配给它的一个属性,然后将该属性传递给外部文件中的一个函数 (import "Scripts.js" as Scripts)

我首先想到的是(在我看来)最明显的方法:

//MyComponent.qml

Item {
    id: comp
    
    // property var target: comp
    // doesn't work either
    property var target: this

    ...

    onActiveFocusChanged: {
        // Scripts.foo(this)
        // and Scripts.foo(tf)
        // don't work either
        if(this.activeFocus) {
            Scripts.foo(target)
        }
    }
}

但这不起作用(将 activeFocus 提供给组件后窗口崩溃)。

所以,我默认将 undefined 分配给目标:

...
property var target: undefined
...

然后在声明时分配组件本身:

MyComponent {
    id: myComponent
    ...
    target: this
    // target: myComponent
    // also works
    ...
}

当 activeFocus 被触发时,一切正常。有人可以告诉我为什么/我做错了什么吗?

不可能将组件本身分配给组件属性?

以及为什么在宣布后并非不可能做到这一点?

【问题讨论】:

  • 您可以使用 id 属性作为指向实例的指针,我不太确定 this 是否按您预期的方式工作。
  • @folibis 谢谢你的评论。我已经尝试使用 id 而不是 this 关键字,但这也不起作用。

标签: javascript qt qml qt5


【解决方案1】:

正如 folibis 已经评论的那样,您应该使用 ids 而不是 this 关键字。看看下面的SO post。

import QtQuick

Window {
    id: root
    width: 800
    height: 600
    visible: true
    title: qsTr("Hello Component")

    function foo(parameter) { console.log(parameter) }

    component MyComponent : Item {
        id: component

        property var target: component

        Component.onCompleted: {
            root.foo(component.target)
            root.foo(component)
        }
    }

    MyComponent {}
    MyComponent { target: root }
}

这没有问题。

import QtQuick

Window {
    id: root
    width: 800
    height: 600
    visible: true
    title: qsTr("Hello Component")

    function foo(parameter) { console.log(parameter) }

    component MyComponent : Item {
        id: component

        property var target: component

        onActiveFocusChanged: {
            if(component.activeFocus)
                root.foo(target)
        }
    }

    MyComponent { id: test }

    Component.onCompleted: test.forceActiveFocus()
}

【讨论】:

  • 谢谢你的回答!我已经尝试使用 id 而不是 this 关键字,但这也不起作用。
  • 编辑您的问题以显示无效的内容。我的示例向您展示了如何使用 id 来做您想要做的事情。至少从你分享的 sn-ps 中我可以理解。
  • 在组件内部,默认为属性提供 id 或 this 关键字,但没有任何效果 (property var target: this / property var target: comp //the id)。但是,如果我在声明组件时将值 this 或 id (comp) 分配给属性,则一切正常。
  • 我添加了另一个没有任何问题的示例。我不明白你的问题。
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多