简体   繁体   English

QML中JS文件中的模型

[英]Models in JS file in QML

Can I put my Models-objects in JS file, and then reuse like a shared model? 我可以将模型对象放在JS文件中,然后像共享模型一样重用吗? It should look like this: 它看起来应该像这样:

//Models.JS
var myModel = ListModel {}

No, you cannot use QML types in JS (I assume it is Qt 4.x). 不,您不能在JS中使用QML类型(我假设它是Qt 4.x)。 If by "reuse" you mean share (like in global variable), you can put your model in global context as a context property. 如果通过“重用”来表示共享(例如在全局变量中),则可以将模型作为全局属性放置在全局上下文中。 See QDeclarativeContext::setContextProperty() . 参见QDeclarativeContext :: setContextProperty() Another option would be create C++ model, where all instance would share same state. 另一种选择是创建C ++模型,其中所有实例将共享相同的状态。

If you don't want to have a single global instance, you can declare ListModel { id: myModel } in root element, and access it from children (even declared in other files). 如果您不希望有一个全局实例,则可以在根元素中声明ListModel { id: myModel } ,然后从子级访问它(甚至在其他文件中声明)。

Item {
    ListModel { id: myModel }
    Listview {
        id: one
        model: myModel
    }
    Listview {
        id: two
        model: myModel
    }
    // etc
}

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

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