Dynamically create ListModel in QML

前端 未结 3 1261
花落未央
花落未央 2021-02-05 22:37

When I need to create any QML component in runtime, I can use that guide: http://qt-project.org/doc/qt-5/qtqml-javascript-dynamicobjectcreation.html

i.e. just call Qt.cr

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 22:48

    I am a JS developer who writes QtQuick applications and this is something I have tried on with multiple solutions.

    Short answer to managing models in JavaScript inside QML is that it's a nightmare. I would advice you to write a small sub-class of QAbstractListModel which internally uses QJsonArray as its data source, so that it makes it easier to understand the data structure in C++ as well as in its usage inside QML. Follow the instructions to create QML types from C++ here.

    If you still want to do it inside JavaScript, another approach is the following:

    function createNewList() {
        var newListModel = Qt.createQmlObject('import QtQuick 2.2; \
            ListModel {}', parent);
        return newListModel;
    }
    

    However this has some serious memory leak problems even after using gc()

    If your primary concern is having ListModels inside ListModels, this following simple thing works for me (there is an implicit type conversion between array of objects and ListModels inside ListModels I think)

    property ListModel items: ListModel {}
    
    function addComplexItem() {
        items.append({
            "key": "People",
            "arr": [
                {
                 "arrItemName": "John",
                 "arrItemValue": 18,
                },
                {
                 "arrItemName": "Kerry",
                 "arrItemValue": 21,
                },
                {
                 "arrItemName": "Mike",
                 "arrItemValue": 19,
                }    
            ]});
    }
    
    
    // Usage
    Component {
        id: viewDelegate
    
        Item {
            Text {
                text: "List of " + key
            }
            ListView {
                model: arr
                delegate: Rectangle {
                    Text { 
                        text: arrItemName
                    } 
                }
            }  
        }
    }
    

提交回复
热议问题