我有一個ListModel和ListView,用于顯示用戶的通知。ListView有一個add過渡,用于顯示每一次彈出的新通知。現在,我想在ListModel中添加一個時間戳(以分鐘為單位)來顯示通知的時間,但是由于我在創建通知時向ListModel中添加了值,所以我必須每分鐘手動更新模型來改變時間戳,這又會觸發我的add轉換。我怎樣才能更新時間戳而不需要每次都重新添加數值呢?
property int numNotifications: backend_service.num_notifications
onNumNotificationsChanged: {
notifyModel.clear()
for(var x=0; x<numNotifications; x ) {
var notif = backend_service.notifications.get(x);
notificationModel.insert(0, {"name"/span>:notif.name, "time"/span>:notif.time})
}
}
矩形 {
高度。500
寬度: 0.90 * parent.width
錨點 {
top: parent
topMargin: 30 30
左邊:parent.left
leftMargin: 45
}
串列視圖 {
anchors.fill: parent
模型:notificationModel
委托:notificationDelegate
間隔。30
添加。Transition {
NumberAnimation { 屬性。"opacity"; from: 0; to: 1; duration: 1000 }
}
}
}
ListModel {
id: notificationModel
}
組件 {
id: notificationDelegate
行 {
間隔。20
Text { text: name; color: "white" }
Text { text: time; color: "white" }
}
}
time是衡量通知的年齡,以分鐘為單位(1分鐘,2分鐘,等等),我必須更新這個值。該值在backend_service中被自動更新,但是ListModel中保留了它第一次被添加時的舊值。我想在不改變模型的情況下更新那個時間值。有什么方法可以在不每次更新模型的情況下做到這一點,也許可以通過創建一個系結?我也愿意接受其他的方法來完成這個任務。
uj5u.com熱心網友回復:
我的建議是,模型應該持有一個固定的時間戳,而不是一個相對的。然后你可以在你的視圖(委托)中選擇相對于當前時間來顯示它。
property date now: new Date()
計時器 {
正在運行。true true
重復: true true
間隔。60 * 1000 /span> 每分鐘
onTriggered: {
now = new Date()
}
}
組件 {
id: notificationDelegate
行 {
間隔。20
Text { text: name; color: "white" }
文本 {
顏色: "白"
文本。{
var diff = now - time
//顯示相對時間,像這樣...
if (diff > [1 minute]) {
return "1分鐘前"。
} else if (diff > [2 minutes] ) {
return "2分鐘前"。
}
else ... // etc.
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/310163.html
標籤:
