Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt从文件中读取QML数据_Qt_File_Model - Fatal编程技术网

Qt从文件中读取QML数据

Qt从文件中读取QML数据,qt,file,model,Qt,File,Model,我有data.txt,其中的数据如下: ListElement{ longitude: "0"; latitude: "0"; height: "-700.114"; } ListElement{ longitude: "0"; latitude: "1"; height: "-698.214"; } ListElement{ longitude: "0"; latitude: "2"; height: "-695.955"; } ListElement{ lon

我有data.txt,其中的数据如下:

    ListElement{ longitude: "0"; latitude: "0"; height: "-700.114"; }
    ListElement{ longitude: "0"; latitude: "1"; height: "-698.214"; }
    ListElement{ longitude: "0"; latitude: "2"; height: "-695.955"; }
    ListElement{ longitude: "0"; latitude: "3"; height: "-706.116"; }
    [...]
我需要像那样将这些数据添加到data.qml中

 import QtQuick 2.1

Item {
    property alias model: dataModel


//! [0]

ListModel{
    id: dataModel
    ListElement{ longitude: "0"; latitude: "0"; height: "-700.114"; }
    ListElement{ longitude: "0"; latitude: "1"; height: "-698.214"; }
    ListElement{ longitude: "0"; latitude: "2"; height: "-695.955"; }
    ListElement{ longitude: "0"; latitude: "3"; height: "-706.116"; }
    [...]

     }
}

如何做到这一点?

作为一个介绍,通常最好保持数据格式的通用性,而不是QML代码。QML是为GUI设计的,如果您想保持代码的通用性和可维护性,那么避免混合应用程序逻辑和GUI代码是很重要的。您可以使用JSON格式,并从C++加载它,或者如果您仍然从QML加载它,可以直接使用<代码> JSON.PARSE < /Cord>JavaScript函数> < /P> 也就是说,您可以将QML模型放在一个单独的.QML文件中,例如:

DataModel.qml

ListModel {
    ListElement{ longitude: "0"; latitude: "0"; height: "-700.114"; }
    ListElement{ longitude: "0"; latitude: "1"; height: "-698.214"; }
    ListElement{ longitude: "0"; latitude: "2"; height: "-695.955"; }
    ListElement{ longitude: "0"; latitude: "3"; height: "-706.116"; }
 }
然后使用该方法创建组件,然后创建对象,您可以通过这种方式使用:

function loadModel() {
    // Create the component
    var component = Qt.createComponent("DataModel.qml");

    if (component.status == Component.Ready) {
        // Instantiate the object given a parent
        var model = component.createObject(qmlParentId);

        // Assign the newly created object to your property
        root.model = model
    }
}

加载后,您的模型将可用。

但是我需要将文本从txt文件放到ListModel{},然后最接近的是来自QML的“Qt.createQmlObject”,它接受一个字符串。但是没有“从txt文件中放入文本”这样的东西。除非你有很好的理由(你可能有),否则这种方法在我看来是有缺陷的。