How to find QML item by its string id?

醉酒当歌 提交于 2019-12-05 05:20:46

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.

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)
}
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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!