Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.
How to expose lists to QML
English Ελληνικά
How to expose lists to QML
Which class to use?
QDeclarativeListProperty [doc.qt.nokia.com] allows you to expose list like properties to QML. When implementing the function pointers in this class, memory management will be taken care of for you and the bindings will work correctly as well. Using a standard QList [doc.qt.nokia.com] instead of QDeclarativeListProperty, will not take care of memory management and can cause your application to leak. In addition QList does not provide notification signals when children change. So when simply using a QList, the bindings won’t work properly either. QDeclarativeListProperty is hence the recommended class to use for lists in QML.
Which constructor to use?
QDeclarativeListProperty provides 2 constructors. The first one [doc.qt.nokia.com] taking a QList is there for convenience and should only be used for prototyping since it does not clean up memory for you. It still connects up the bindings properly and is therefore recommended over using a simple QList.
The second QDeclarativeListProperty constructor [doc.qt.nokia.com] constructs a QDeclarativeListProperty from a set of operation functions. It works by passing functions to be called when appending, clearing, counting and getting the current position, but only the append function is necessary to implement. This is the constructor you should use in production code.
Example on how to use QDeclarativeListProperty
The following example shows how the QDeclarativeListProperty::AppendFunction [doc.qt.nokia.com] and QDeclarativeListProperty::ClearFunction [doc.qt.nokia.com] can be implemented:
Due to the way that QDeclarativeListProperty works it is necessary to keep the QList around while the property is valid which is why it is a member of the class here.
The following QML file shows how the class above can be used and cleared in qml.
Note that in order to clear it, it is necessary to do:
as Javascript doesn’t know when to clear it otherwise.
The Qt documentation provides the following example [doc.qt.nokia.com] that can be useful to have a look at as well.
Dynamic alteration of lists
Dynamic alteration of lists is not well supported right now, due to issues with bindings and lists. The current way to alter a list is to assign a new list in its place.