在 QML 中动态创建 ListModel

2022-01-19 00:00:00 qt5 runtime qml javascript

当我需要在运行时创建任何 QML 组件时,我可以使用该指南:http://qt-project.org/doc/qt-5/qtqml-javascript-dynamicobjectcreation.html

When I need to create any QML component in runtime, I can use that guide: http://qt-project.org/doc/qt-5/qtqml-javascript-dynamicobjectcreation.html

即只需调用 Qt.createComponent 和 component.createObject

i.e. just call Qt.createComponent and component.createObject

但我找不到如何在运行时创建 ListModel?使用 qml,而不是在 C++ 中.

But I couldn't find how to create ListModel at runtime? with qml, not in c++.

你可以问,我为什么需要它.所以,我有一个嵌套的 ListModel:有 外层模型,它的代表包含 内层模型.所以当我调用outer_model.append({}) 时,我必须为inner model 传递新创建的ListModel.我不能在外部委托中使用静态定义的 inner model,因为我无法在运行时访问这样的模型.对了,能不能通过某种方式访问​​?

You can ask, why I need it. So, I have a nested ListModel: there is outer model, which delegates contained inner models. So when I'm calling outer_model.append({}), I must pass newly created ListModel for inner model. I cannot use statically defined inner model in outer delegate, because I cannot access such model in runtime. By the way, can it be accessed somehow?

附:也许尝试在 javascript 中管理模型是完全错误的想法?

P.S. Maybe it's completely wrong idea to try managing models in javascript?

推荐答案

试试这个:

Component {
    id: someComponent
    ListModel {
    }
}

function createModel(parent) {
    var newModel = someComponent.createObject(parent);
    return newModel;
}

相关文章