Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find QML item by its string id?

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.

like image 860
Werolik Avatar asked Jul 03 '15 12:07

Werolik


2 Answers

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...)

} 
like image 74
Amfasis Avatar answered Oct 04 '22 05:10

Amfasis


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.

like image 23
Mitch Avatar answered Oct 04 '22 06:10

Mitch