c++qmllistmodel

Chage ListModel data in qml file using C++


There is an example : http://doc.qt.io/qt-5/qtdatavisualization-qmlscatter-example.html of using qml and QtQuick to create a 3D scatter.

How can I chage (delete, append, clear) ListModel data in Data.qml file using C++ code?

Data.qml

import QtQuick 2.1

Item {
     property alias model: dataModel
     property alias modelTwo: dataModelTwo
     property alias modelThree: dataModelThree

     ListModel {
         id: dataModel
         ListElement{ xPos: -10.0; yPos: 5.0; zPos: -5.0 }
         ListElement{ xPos: -9.0; yPos: 3.0; zPos: -4.5 }
         ListElement{ xPos: -8.5; yPos: 4.1; zPos: -4.0 }
         ...
     }
     ...
}

Solution

  • If you want to modify the model from C++, you can register an object that implements QAbstractItemModel to the QML runtime.

    QAbstraactItemModel is a fairly complex class, there are helpful derived types that may make implementation easier, but that depends on your use case. For instance, QAbstractListModel is useful for lists, as opposed to tables, and QStandardItemModel is useful for data that can be easily modeled at QStandardItems.

    Once you've implemented the model in C++ you need to make it available to the QML runtime. This is done using setContextProperty on QQmlContext. Generally the QQmlContext you want is the rootContext() of your QQmlEngine.

    The registration might look something like this:

    int main(int argc, char **argv) {
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        MyListModel *model = new MyListModel;
    
        engine.rootContext()->setContextProperty("myListModel", model);
        engine.load(":/myqmlapp.qml");
        app.exec();
        [...]
    }
    

    To access the model from within QML you use the name that it was registered with, in this case myListModel:

    import QtQuick 2.7
    
    Item {
        ListView {
            model: myListModel
        }
    }