C

Qt Quick Ultralite listmodel Example

/****************************************************************************** ** ** Copyright (C) 2020 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Quick Ultralite module. ** ** $QT_BEGIN_LICENSE:COMM$ ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** $QT_END_LICENSE$ ** ******************************************************************************/
#pragma once #include <qul/model.h> #include <string> #include <vector> // To create a custom ListModel<T>, we need to declare a type T that holds // the data for each element and is equality comparable. // // Here, the data type is AlarmData and it holds the number of seconds before // the alarm should trigger (negative if it has already triggered), as well // as a running flag. struct AlarmData { int seconds = 0; bool running = false; }; inline bool operator==(const AlarmData &lhs, const AlarmData &rhs) { return lhs.seconds == rhs.seconds && lhs.running == rhs.running; } // Declare our AlarmModel. // // The only requirement is that we implement the pure virtual functions // count() and data() from ListModel. // // We add the other functions to allow our UI to affect the model. struct AlarmModel : Qul::ListModel<AlarmData> { private: std::vector<AlarmData> m_data; public: // Implement the ListModel interface int count() const override { return m_data.size(); } AlarmData data(int index) const override { return m_data[index]; } // Construct the model with some example data. AlarmModel() : m_data({{-5, false}, {11, false}, {23, true}}) {} // Our app shows a "Pause"/"Unpause" button on each alarm entry. // This applies the requested state change to the model and then // informs the view about the change with the dataChanged() call. void togglePause(int index) { m_data[index].running = !m_data[index].running; dataChanged(index); } // There is a button to remove an alarm entry. This function removes // the data for the entry and then calls modelReset() to inform the // view that the number of entries in the model has changed. void remove(int index) { m_data.erase(m_data.begin() + index); modelReset(); } // Adding a new alarm entry is similar to removing one above. void addEntry(int seconds) { m_data.push_back({seconds, true}); modelReset(); } // A Timer calls this function on the model every second to update // the state of the alarms. void tick() { for (size_t i = 0; i < m_data.size(); ++i) { auto &entry = m_data[i]; if (entry.running || entry.seconds <= 0) { entry.seconds--; dataChanged(i); } } } };