简体   繁体   中英

Appending Elements to QML ListModel from C++

I am following this example in order to understand how to work with a QList as a ListModel for QML.

I would like to modify the list from C++. Therefore I put the list into a new QObject to be able to use a timer. In the timer callback I modify an existing element's color and append a new element to the list.

void MyObject::setList(QList<QObject *>* l)
{
    list = l;
    QTimer* timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(addElement()));
    timer->start(2000);
}

void MyObject::addElement()
{
    list->append(new DataObject("Item 1", "red"));
    ((DataObject *) list->at(0))->setColor("blue");
}

The color change is shown in QML, however the length of the list in QMLs ListView does not change. What am I missing? What steps are neccessary to make QML aware of the list's size change?

I understand the color and name properties are registered through the Q_PROPERTY makro

Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)

How do I translate this to the list's length?

A QList<QObject*> is the simplest but also the dumbest type of data model you could use. It has no means to signal for internal changes so the view can update itself.

You could force updates by exposing the list as a property that has the NOTIFY signal. However, that is very inefficient, and will force the recreation of every list view delegate each and every time. This can get ugly very fast as the number of elements grows.

You should consider implementing a proper QAbstractListModel with all its bells and whistles. Then changes in the list will be reflected on the qml side in the most efficient and adequate manner possible. Or perhaps use the generic model I've outlined here , it is quite flexible because it also allows population with declarative qml code in additions to using the functions. You can also define the actual object types in qml without the need to recompile the C++ stuff for each and every new type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM