Access dynamic QML objects from C++
-
Hi,
Is anyone aware of how to access and store dynamically created QML objects? I used the following code suggested on Qt Site for creating dynamic QML objects and trying to store them in a QML list type
@
property list<Button> listButtons: [
Button{ }
]
function addButton(buttonname) {
console.log("Creating Pin: "+buttonname)
var component = Qt.createComponent("Button.qml");
if (component.status == Component.Ready)
{
var newbutton = component.createObject(node);
newbutton.x = 20;
newbutton.y = 30;
listButtons.append(newbutton) //I get a error here: listButtons.append [undefined] is not a function
}
else
{
console.log("Unable to create button: "+buttonname)
}
}
@
Thank you.CV
-
You can store your created objects in a javascript array or object. Declare your javascript variable in a external javascript file and import it in QML file, it will make your javascript variable accessible at global scope (so anywhere in your QML file).
-
... and about your error, do "listButtons.push(newButton)".
Be careful with list type properties because it's just hold a copy of the object, consider it in update and delete operations. Here some useful docs :
-
Sry, I should have mentioned. I was trying to access these objects from C++ application. Do you think I can still access these objects if I write javascript?
-
In this case, why don't you create these objects directly in C++ ?
-
You can always access QML objects , but depend on what you want to do !!! it means one way communication or two , if one way from which side !!?
1st ::If your object is QML only and sometimes you need to change it from C++ , then the best way is to define an object for its parent and access that object property:::2nd :: if your object is in QML just updates a variables in C++ you can just send a signal (with parameters) from QML to c++ :::
3rd :: if your Application ((like TextInput)) need two way access to C++/QML (both update each other ) then you need to make a Q_PROPERTY
Also Read here :: http://doc.qt.nokia.com/4.7-snapshot/qml-extending.html
-
Satmosc: Thanks for your reply. So looks like the only way I can access the children of a QML component as mentioned here and using the objectName property:
http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html#locating-child-objects
I was looking for a better way i.e. storing pointers to dynamically created QML components in a list. Anyways, this works for now