Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update value in Qml List View?

I have a ListModel which stores a string "cityName" and a real value "TimeZoneOffset". As the name suggests, cityName holds the name of the city and TimeZoneOffset holds the time offset (from UTC) in minutes.

ListModel {
  id: worldCity

  ListElement {
   cityName: "London"
   TimeZoneOffset: 0
  }

  ListElement {
   cityName: "Amsterdam"
   TimeZoneOffset: 120
  }
}

This model is then used in a ListView. The ListView has a structure as shown in the code sample below.

ListView {
  model: worldCity
  currentIndex: -1

  delegate: ListItem.Standard {
    text: cityName        
    Label {
      text: timeOffSet + currentSystemTime
    }
  }
}

As you can see, my ListView is showing a modified output instead of directly outputting the listModel element. I need to update the ListView elements every minute to show the current time at a city. I plan on using a Timer to update it every minute.

How do I update every listView element?

like image 326
Nik Avatar asked Oct 15 '25 10:10

Nik


1 Answers

To me, updating the model directely doesn't seems the right option, here is an simplified and enhanced version of your code that does the thing right :

import QtQuick 2.0

Rectangle {
    width: 200;
    height: 400;

    property real currentTimestamp;

    function updateTime () {
        var now = new Date ();
        currentTimestamp = now.getTime ();
    }

    Timer {
        interval: 60000;
        repeat: true;
        running: true;
        onTriggered: { updateTime (); }
    }
    ListView {
        anchors.fill: parent;
        model: ListModel {
            ListElement { cityName: "London";     timeOffSet: 0;   }
            ListElement { cityName: "Amsterdam";  timeOffSet: 120; }
            ListElement { cityName: "Paris";      timeOffSet: 60;  }
        }
        delegate: Column {
            anchors {
                left: parent.left;
                right: parent.right;
            }

            Text {
                text: model.cityName;
                font.bold: true;
            }
            Text {
                text: Qt.formatTime (new Date (currentTimestamp + (model.timeOffSet * 60000)), "hh:mm A");
            }
        }
    }
    Component.onCompleted: { updateTime (); }
}
like image 184
TheBootroo Avatar answered Oct 17 '25 22:10

TheBootroo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!