How to find QML item by its string id?
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.
Based on the answer from Phrogz, if you don't want an explicit map, you can assign the components to properties and then reference these with the [] operator:
Item {
id: page
property Component foo: Rectangle { color: "yellow" }
property Component bar: Item { }
Component.onCompleted: console.log(page["foo"], page["bar"])
//qml: QQuickRectangle(0x...) QQuickItem(0x...)
}
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));
}