【问题标题】:Is there a way to get to a component with it's id in string format in qml?有没有办法在 qml 中以字符串格式获取其 id 的组件?
【发布时间】:2019-03-04 10:49:00
【问题描述】:

在 javascript 的 qml 中的一个函数中,我有一个组件的 id。 这是我正在尝试做的一个简单示例:

function teste(val) {
    var elem = "objectId"
    var objectThatINeed = submenu1.findObjectById(elem)
    objectThatINeed.someValueIWantToChange = val
}

函数findObjectById不存在,只是为了说明我想要做什么。

我想获得对该对象的引用(不,我不想像objectId.someValueIWantToChange = val 那样直接访问它)然后更改属性。

如果 id 不可接受,我看到的另一个可以使用的属性是 objectName,甚至是自定义属性...

这样的事情怎么办?

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    在 QML 中,id 并不是一个真正的属性,并且很难检索它(它更像是一个变量名)。但是您可以使用 objectName 之类的属性来查找特定父级的子级:

    Item {
            id: theParent
            Item {
                objectName: "id1"
            }
            Item {
                objectName: "id2"
            }
            Item {
                objectName: "id3"
            }
        }
    
        function findChild(id, root) {
            for (var i = 0; i !== root.children.length; ++i) {
                const child = root.children[i];
                if (child.objectName === id) {
                    console.log("Found");
                    return child;
                }
            }
                    return null;
        }
    

    【讨论】:

    • 他们为什么不添加这样的东西
    • root.children 未定义
    猜你喜欢
    • 2020-05-14
    • 2017-03-20
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2014-11-19
    • 2011-05-21
    相关资源
    最近更新 更多