首页 > 解决方案 > 在 QML 中填充 Combobox 模型时如何使用 csv 列表?

问题描述

我正在尝试使用 csv 列表在 QML 中构建动态组合框。我正在将列表转换为数组,它看起来应该可以工作,但没有这样的运气。如果我使用完全相同的格式手动插入数组,它确实可以工作。我错过了什么?

我可以通过简单地复制和粘贴 console.log(model) 的输出来使其工作,但在直接使用时不能。

首先,我在组件构建函数中将 csv 转换为数组

    var combo_list =[];
    // get csv count and then convert list to an array
    Default_Value.split(",").forEach( (x,y) => combo_list.push(x));       
    // now I add it to my options and return it to my QML component
    var options = {
        "options_ComboList":Qt.binding(function() {return String(JSON.stringify(combo_list))})};

    question_options_Object = component_options_object.createObject(mainCol,options);

在我的 QML 组件中

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Dialogs.qml 1.0
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.3
import "."

Item {
    id: options_entry_item
    height: 140

    //inputs to question
    property var options_ComboList  //array lands here

            ComboBox {
                id: comboBox
                //model: JSON.stringify(options_ComboList)  // does not work, adds slashes around commas
                //model: options_ComboList // does not work, but outputs a correct array format when sent to console
                model: ["0:Use DipSwitch Settings","1:Safe/AGM-1 Bulk 14.1v","2:FLA 1(Starter) Bulk 14.8"]  // when copied/pasted from console.log of model: options_ComboList it works perfectly

            }

            Component.onCompleted: {
                console.log("Combobox model: "+comboBox.model);
           // output is: Combobox model: ["0:Use DipSwitch Settings","1:Safe/AGM-1 Bulk 14.1v","2:FLA 1(Starter) Bulk 14.8"]

            }
        }

没有错误被发出

标签: qtcomboboxmodelqml

解决方案


经过一番研究,我发现了问题所在。我需要做的就是解析进入我的模型的数组所以我对模型的输入变成了。

ComboBox {
    id: comboBox
    model: JSON.parse(options_ComboList)
}

希望这对其他人有帮助!


推荐阅读