[英]How to update ListElement (QML) value field with dynamically updating property
在下面的代碼中,屬性__operatingModus_season
每 30 秒更新一次。 但在前端,我看不到任何價值或變化。 如果我錯了,請多多指教。
ListModel{
id: tileListModelBetriebsmodus
Component.onCompleted: {
if(__is_automatik_mode_ON){
tileListModelBetriebsmodus.append({"tileListSource": "../../images/HausScreen/operatingModeAuto.png",
"tileListText": getFrontendText("AUTO"),
"tileListValue": __operatingModus_season
})
}else{
tileListModelBetriebsmodus.append({"tileListSource": "../../images/HausScreen/hamburgerfinger.png",
"tileListText": getFrontendText("MANUAL"),
"tileListValue": __operatingModus_season
})
}
}
}
這種將項目添加到 ListModel 的方式不會使它們成為動態的,這些值是當場存儲的。
您可以像這樣創建屬性綁定:
ListModel{
id: tileListModelBetriebsmodus
Component.onCompleted: {
if(__is_automatik_mode_ON){
tileListModelBetriebsmodus.append({"tileListSource": "../../images/HausScreen/operatingModeAuto.png",
"tileListText": getFrontendText("AUTO"),
"tileListValue": Qt.binding(function() { return __operatingModus_season })
})
}else{
tileListModelBetriebsmodus.append({"tileListSource": "../../images/HausScreen/hamburgerfinger.png",
"tileListText": getFrontendText("MANUAL"),
"tileListValue": Qt.binding(function() { return __operatingModus_season }
})
}
}
}
注意我沒有測試這個,如果你添加一個最小的工作示例,我可以這樣做。
Amfasis 的回答表明使用Qt.binding()
是在正確的軌道上,除了 Qt 不允許將綁定對象直接分配給 ListElement。 但是,它允許分配普通的 JS 函數對象。 因此,您必須分兩步完成:
第 1 步:將動態評估的 ListElement 角色定義為 JS 函數(提示:您還可以使用箭頭語法使其更具可讀性),例如:
ListElement {
dynamicLabel: () => config.useLabelA ? labelA : labelB
}
第 2 步:在目標項和模型角色之間的委托中設置綁定:
ListView {
delegate: Text {
Component.onCompleted: {
text: Qt.binding(model.dynamicLabel)
}
}
}
請注意需要通過Component.onCompleted
因為您不能直接執行text: Qt.binding(model.dynamicLabel)
(QML 吐出錯誤“在綁定聲明中使用 Qt.binding() 無效。”)。
你不能只做text: model.dynamicLabel
,因為它只會在初始分配時評估一次 JS 函數,但如果config.useLabelA
更改,則不會更新。 這就是您需要Qt.binding()
包裝器的目的。
基於 Romain Pokrzywka 的回答:
text: valuedUpdated() ? model.dynamicLabel : ""
text: valuedUpdated() ? model.dynamicLabel : ""
將在值更新時進行評估。 valuedUpdated() 是一個 Q_PROPERTY,它返回 true。 每當值更新時,都可以發出通知信號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.