how to edit the property of dynamically created object?
-
according to the tutorial,Qml can use createComponent() + createObject() to dynamically create objects
but how to edit the property of these objects
For example:
//dyRec.qml
Rectangle {
id: rect
TextEdit {
id: rectText
text: qsTr("Default")
}
}//main.qml
Window {
id: root
var dyRect = Qt.createComponent("dyRec.qml")
var dyRectObj = dyRect.createObject(root)
//Here I want to edit the text of TextEdit in Rectangle, how to do it
dyRectObj.rectText.text = qsTr("1111") //<--Error
} -
You need to expose the
text
as a property. Theid
you set in your QML file is local - visible only inside of that same file. When you try to access it from another file (main.qml), it will never work. Does not matter if it is a dynamic component or not.So, for example:
//dyRec.qml Rectangle { property alias text: rectText.text id: rect TextEdit { id: rectText text: qsTr("Default") } } // main.qml var dyRect = Qt.createComponent("dyRec.qml") var dyRectObj = dyRect.createObject(root) dyRectObj.text = qsTr("1111")