How to find QML item by its string id?

2019-04-28 17:11发布

I have a string id of an object I need to find in QML tree. For example:

var idToFind = "myBtnId"

Can I do something like the following?

var objectThatINeed = myMainWindow.findObjectById(idToFind)

As far as I understand I can use objectName for this purpose (at least from C++). Can I still reuse existing ids somehow without introducing the names?

I want to use this object as a parent for some other dynamically created controls.

3条回答
贼婆χ
2楼-- · 2019-04-28 18:02

No, you have to use objectName or some other property.

The id Attribute:

Once an object instance is created, the value of its id attribute cannot be changed. While it may look like an ordinary property, the id attribute is not an ordinary property attribute, and special semantics apply to it; for example, it is not possible to access myTextInput.id in the above example.

查看更多
别忘想泡老子
3楼-- · 2019-04-28 18:03
QJSValue MyEngine::getQmlObjectById(const QString& id) {
    QV4::ExecutionEngine *v4 = QV8Engine::getV4(m_JSEngine);
    QV4::Scope scope(const_cast<QV4::ExecutionEngine *>(v4));
    QV4::ScopedString name(scope, v4->newString(id));
    return QJSValue(v4, v4->currentContext->getProperty(name));
}
查看更多
神经病院院长
4楼-- · 2019-04-28 18:15

If you know the IDs of all items you want beforehand, you can create an object map for them and use that to look them up. For example:

Item {
    property var idMap: ({ foo:foo, bar:bar })
    Rectangle { id:foo }
    Item { id:bar }

    function findItemById(id) {
      return idMap[id];
    }

    Component.onCompleted: console.log(findItemById('foo'), findItemById('bar'))
    // qml: QQuickRectangle(0x1479e40) QQuickItem(0x148fbf0)
}
查看更多
登录 后发表回答