首页 文章

从C更改QML Listview委托

提问于
浏览
1

我试图从C更改qml listview的委托,但目前我坚持如何更改代表委托属性的别名 .

Update on details: 我在分开的qml文件中有多个代理,在我的应用程序中有很多屏幕,每个屏幕都有不同的listview UI,我想要的是:

将委托文件名传递给C函数>>> C函数集listView的委托属性(或类似的东西)>>> listview加载相应的委托 .

我的qml文件如下所示:

Item {
    id: root
    property alias listViewDelegate: listView.delegate

    ListView{
        id: listView
        delegate: MyDelegate{} // I have MyDelegate.qml file, it's working well
        model: listModel
    }

    // List model
    MyListModel {
        id: listModel
    }
}

我尝试使用setProperty()方法从C更改listViewDelegate别名但没有运气(实际上是错误) .

qmlObj->setProperty("listViewDelegate", componentDelegate);

怎么做到这一点?或者任何人都可以建议我更好的方法来实现它?谢谢!

3 回答

  • 0

    我认为有更好的方法来做到这一点 .

    脚步:

    1)在c侧创建模型 .

    class Model : public QObject {
      Q_OBJECT
      Q_PROPERTY(qint32 status READ status WRITE setStatus NOTIFY statusChanged)
    public:
      Model(QObject *parent = Q_NULLPTR);
      ...
    }
    

    2)通过setContextProperty将Model对象传递给qml

    Model model;
    engine.rootContext()->setContextProperty("model1", &model);
    

    3)在Model.status上绑定ListView的委托

    ListView {
        id: listview
        anchors.fill: parent
        spacing: 20
        model: listmodel
        delegate: model1.status === 0 ? delegate1 : delegate2
    }
    

    4)现在你可以通过c侧的setStaus()更改委托 .

    model.setStatus(1);
    
  • 2

    必须将属性listViewDelegate分配给ListView,以便在修改ListViewDelegate属性时,将通知ListView并更新委托 .

    Item {
        id: root
        property Component listViewDelegate: myDelegate
    
        MyDelegate { 
              id:  myDelegate
        }
    
        ListView{
            id: listView
            delegate: listViewDelegate
            model: listModel
        }
    
        // List model
        MyListModel {
            id: listModel
        }
    }
    
  • 2

    感谢大家,我只想通过使用javascript找到一种方法,看起来很复杂,但它确实有效 .

    我将这个javascript函数添加到我的根项目中

    function loadListViewDelegate(file){
        var component = Qt.createComponent(file);
        if(component && (component.status === Component.Ready))
        {
            listView.delegate = component;
            return file;
        }
        return "";
    }
    

    然后我从C调用此函数,参数是委托qml文件 . 它看起来像这样:

    QMetaObject::invokeMethod(qmlObj, "loadListViewDelegate", Q_RETURN_ARG(QVariant, returnedValue), Q_ARG(QVariant, "delegate_screen_home.qml"));
    

    How to invoke qml javascript method

相关问题