QDeclarativeListProperty add item from qml application
down vote
favorite is there any why to add item to QDeclarativeListProperty from qml file at run time? in a loop, for example:
- var i;
- for(i = 0 ; i < 100 ; ++i)
- {
- listOfItems.append(MyItem {text:"list"+i})
- }
and listOfItems is the QDeclarativeListProperty list…
i don’t want to do that:
- listOfItems:
- [
- MyItem{text:"list val1"},
- MyItem{text:"list val2"},
- ......
- ]
i have a lot of item that should be in this list
5 replies
In order for this to work, you need to implement the AppendFunction [doc.qt.nokia.com] of QDeclarativeListProperty. The example below shows how that can be done. It also implement ClearFunction [doc.qt.nokia.com] so that it cleans up correctly.
- #include <QtDeclarative>
- {
- Q_OBJECT
- Q_PROPERTY(QDeclarativeListProperty<MyObject> getInfo READ getInfo CONSTANT)
- public:
- MyObject()
- {}
- ~MyObject()
- {
- }
- QDeclarativeListProperty<MyObject> getInfo()
- {
- for (int i = 0; i < 10; ++i)
- {
- list << new MyObject();
- }
- return QDeclarativeListProperty<MyObject>(this, 0, &MyObject::appendObject, 0, 0, &MyObject::clearObject);
- }
- static void appendObject(QDeclarativeListProperty<MyObject> *l, MyObject *obj)
- {
- MyObject *object = qobject_cast<MyObject *>(l->object);
- if (object)
- object->list << obj;
- }
- static void clearObject(QDeclarativeListProperty<MyObject> *l)
- {
- qDebug("In clear");
- MyObject *object = qobject_cast<MyObject *>(l->object);
- if (object) {
- foreach (MyObject *o, object->list)
- delete o;
- object->list.clear();
- }
- }
- };
I have a similar requirement: Append item to an initialized list property from QML application at run-time.
This is what we can do right now, at the initialization stage:
- MyElement {
- id: myElement
- listOfItems: [
- MyItem {text: "list val1"},
- MyItem {text: "list val2"}
- ]
- }
This is what I would like to do additionally, at run time:
- myElement.listOfItems.append(MyItem {text: "list val3" });
or:
- MyItem {
- id: myItem3
- text: "list val3"
- }
- myElement.listOfItems.append(myItem3);
But neither “append()” works. This means that QDeclarativeListProperty is static once initialized in QML. This is a big limitation. Refer to the “Birthday Party” example. We have an initial list of guests. Later a new guest wants to join the fun. Will this be possible?
This seems to be a very big limit to QDeclarativeListProperty<T*> properties. I couldn’t find a way to dynamically append items to a QDeclarativeListProperty list from QML nor to dynamically create a new list and replace the old list with a new one. I can’t believe that this was overlooked by Trolltech guys, it’s a serious limitation if you want to do application logic with QML and Javascript, or am I missing a point here?
You must log in to post a reply. Not a member yet? Register here!



