动态添加更多组合框而不重置现有数据

Dynamically add more combobox without resetting exiting data

我希望将更多组合框动态添加到我的视图中。该代码工作正常,并在单击按钮时添加了一个新的组合框。

但是,当我添加一个新的 Combobox 时,现有 Combobox 中的数据被重置为默认值。如何在不重置先前选择的值的情况下附加另一个组合框。我宁愿不将现有值保存在某些变量中

这是我的代码

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.3

Page {

    id : somepageid
    property int modelList: 0
    property int counter: 0

    // Combobox Listmodel
    ListModel{
        id: listmodel

        ListElement{
            elem: "A"
        }
        ListElement{
            elem: "B"
        }
        ListElement{
            elem: "C"
        }
    }

    // Add more item to Listview
    function addMore(){
        if(counter < listmodel.count){
            counter++
            modelList++
            listid.model = modelList
        }
    }

    // Button
    Button{
        id: testButton
        text: "Click to add Combobox"
        onClicked: {
            addMore()
        }
    }

    // Listview
    ListView{
        id: listid
        model: modelList
        anchors.top:  testButton.bottom
        height: listid.model * 40

        delegate: Row{
            ComboBox{
                id: combo
                textRole: "elem"
                model:listmodel
            }
        }
    }
}

问题是您每次执行 listid.model = modelList 时都会重置 ListView。 您需要为您的列表视图设置一个固定模型并在那里进行更改。

一个示例(应用于您的代码)可能如下所示:

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.3

Page {

    id : somepageid
    property int counter: 0

    // ListView model
    ListModel{
        id: listmodel
    }

    // Add more item to Listview
    function addMore(){
        if(counter < 3){
            counter++
            listmodel.append({elements: [{elem: "A"}, {elem: "B"}, {elem: "C"}]})
        }
    }

    // Button
    Button{
        id: testButton
        text: "Click to add Combobox"
        onClicked: {
            addMore()
        }
    }

    // Listview
    ListView{
        id: listid
        model: listmodel
        anchors.top:  testButton.bottom
        height: listid.model.count * 40

        delegate: Row{
            ComboBox{
                id: combo
                textRole: "elem"
                model: elements
            }
        }
    }
}