How can I find a QML element by its string id?

I have an id

object string that I need to find in a QML tree. For example:

var idToFind = "myBtnId"

      

Can you do something like the following?

var objectThatINeed = myMainWindow.findObjectById(idToFind)

      

As I understand it, I can use objectName

for this purpose (at least from C ++). Is there any way to reuse an existing one id

without typing names?

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

+3


source to share


3 answers


No, you must use objectName

some other property.

Id attribute :



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

+7


source


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));
}

      



+1


source


If you know the IDs of all the items you want in advance, you can create a feature map for them and use them to search. 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)
}

      

+1


source







All Articles