簡體   English   中英

從C ++更改QML Listview委托

[英]Change QML Listview delegate from C++

我試圖從C ++更改qml listview的委托,但目前我堅持如何更改代表委托屬性的別名。

詳細信息更新: 我在單獨的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);

如何實現呢? 還是有人可以建議我實現這一目標的更好方法? 謝謝!

我認為有更好的方法可以做到這一點。

腳步:

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將模型對象傳遞給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);

必須將屬性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
    }
}

謝謝大家,我只是想出了一種使用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"));

如何調用QML JavaScript方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM