访问组合框数据模型

时间:2018-12-08 09:04:07

标签: qt combobox qml qjson

我正在从C ++向QML组合框发送QJsonArray

netlib.h

void discoveryResultChanged(const QJsonArray jsonArray);

netlib.cpp

QByteArray answer_ba = reply->readAll();
QJsonDocument answer_json_doc = QJsonDocument::fromJson(answer_ba);
QJsonObject answer_json_obj = answer_json_doc.object();
QJsonArray answer_json_array = answer_json_obj["printers_array"].toArray();
qDebug() << __func__ << "JSON array: " << answer_json_array;
emit discoveryResultChanged(answer_json_array);

*。qml

    ColumnLayout {
        id: printersColumn
        width: parent.width
        spacing: 8
        Layout.bottomMargin: 8
        Layout.topMargin: 8

        visible: !netlib.discoveryInProgress

        RowLayout {
            width: parent.width

            ComboBox {
                id: printers
                width: parent.width
                anchors.margins: 4
                textRole: "name"
            }

            Connections {
                target: netlib
                onDiscoveryResultChanged: {
                    printers.model = jsonArray // ComboBox model is set to QJsonArray
                }
            }
        }

        RowLayout {
            TextArea {
                text: printers.currentText
                // How to access `printers` ComboBox data model here?
                // I need to access key/values of QJsonArray ... how?
            }
        }

    }

示例QJsonArray

QJsonArray([{“ ip”:“ 10.10.2.22”,“ name”:“ N 0”,“ port”:4000,“ profiles_array”:[{“ config”:“ 0 blah blah blah”,“ id“:0,” name“:”个人资料0-0“},{” config“:” 1等等blah“,” id“:1,” name“:”个人资料0-1“},{” config “:” 2 blah blah“,” id“:2,” name“:”配置文件0-2“}]},{” ip“:” 192.168.1.1“,” name“:” N 1“,” port“:4001,” profiles_array“:[{” config“:” 0 blah blah blah“,” id“:0,” name“:” Profile 1-0“},{” config“:” 1 blah blah blah “,” id“:1,”名称“:”配置文件1-1“},{” config“:” 2等等等等“,” id“:2,”名称“:”配置文件1-2“}] },{“ ip”:“ 172.16.1.1”,“ name”:“ N 2”,“ port”:4003,“ profiles_array”:[{“ config”:“ 0 blah blah blah”,“ id”:0 ,“ name”:“配置文件2-0”},{“ config”:“ 1等等等等”,“ id”:1,“ name”:“配置文件2-1”},{“ config”:“ 2等等等等“,” id“:2,” name“:”个人资料2-2“}]}]))


如何从QML代码上的QJsonArray中访问ComboBox模型TextArea的键/值?

1 个答案:

答案 0 :(得分:0)

通过这种方式,我可以从JsonArray内部访问ID为ComboBox的{​​{1}}模型键/值printers

TextArea