简体   繁体   English

使用C ++在qml文件中的Chage ListModel数据

[英]Chage ListModel data in qml file using C++

There is an example : http://doc.qt.io/qt-5/qtdatavisualization-qmlscatter-example.html of using qml and QtQuick to create a 3D scatter. 有一个示例: http : //doc.qt.io/qt-5/qtdatavisualization-qmlscatter-example.html使用qml和QtQuick创建3D散点图。

How can I chage (delete, append, clear) ListModel data in Data.qml file using C++ code? 如何使用C ++代码修改(删除,附加,清除)Data.qml文件中的ListModel数据?

Data.qml 数据文件

import QtQuick 2.1

Item {
     property alias model: dataModel
     property alias modelTwo: dataModelTwo
     property alias modelThree: dataModelThree

     ListModel {
         id: dataModel
         ListElement{ xPos: -10.0; yPos: 5.0; zPos: -5.0 }
         ListElement{ xPos: -9.0; yPos: 3.0; zPos: -4.5 }
         ListElement{ xPos: -8.5; yPos: 4.1; zPos: -4.0 }
         ...
     }
     ...
}

If you want to modify the model from C++, you can register an object that implements QAbstractItemModel to the QML runtime. 如果要从C ++修改模型,可以将实现QAbstractItemModel的对象注册到QML运行时。

QAbstraactItemModel is a fairly complex class, there are helpful derived types that may make implementation easier, but that depends on your use case. QAbstraactItemModel是一个相当复杂的类,有一些有用的派生类型可以QAbstraactItemModel实现,但这取决于您的用例。 For instance, QAbstractListModel is useful for lists, as opposed to tables, and QStandardItemModel is useful for data that can be easily modeled at QStandardItems . 例如,与表相反, QAbstractListModel对于列表有用,而QStandardItemModel对于可以在QStandardItems轻松建模的数据有用。

Once you've implemented the model in C++ you need to make it available to the QML runtime. 使用C ++实现模型后,您需要使其可用于QML运行时。 This is done using setContextProperty on QQmlContext . 这是通过使用QQmlContext setContextPropertyQQmlContext Generally the QQmlContext you want is the rootContext() of your QQmlEngine . 一般来说, QQmlContext你想要的是rootContext()你的QQmlEngine

The registration might look something like this: 注册可能看起来像这样:

int main(int argc, char **argv) {
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    MyListModel *model = new MyListModel;

    engine.rootContext()->setContextProperty("myListModel", model);
    engine.load(":/myqmlapp.qml");
    app.exec();
    [...]
}

To access the model from within QML you use the name that it was registered with, in this case myListModel : 要从QML中访问模型,请使用其注册名称,在本例中为myListModel

import QtQuick 2.7

Item {
    ListView {
        model: myListModel
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM