#include "calendarlistmodel.h" #include #include #include "database.h" struct CalendarListModel::Calendar { QString name; }; CalendarListModel::CalendarListModel(QObject *parent) : QAbstractListModel{parent} , m_calendars{} { fetch(); } CalendarListModel::~CalendarListModel() { qDeleteAll(m_calendars); } QVariant CalendarListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) { return {}; } return section; } int CalendarListModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return m_calendars.count(); } QHash CalendarListModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); roles[Name] = "name"; return roles; } void CalendarListModel::fetch() { Database::query([]() { QSqlQuery query("select label from campsite order by label"); QVector calendars; while (query.next()) { Calendar calendar{query.value(0).toString()}; calendars.append(calendar); } return calendars; }).then([this](const QVector &calendars) { if (calendars.empty()) { return; } beginInsertRows(QModelIndex(), 0, calendars.count() - 1); for (const Calendar &calendar : calendars) { m_calendars.append(new Calendar(calendar)); } endInsertRows(); }); } QVariant CalendarListModel::data(const QModelIndex &index, int role) const { if (!checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid | QAbstractItemModel::CheckIndexOption::ParentIsInvalid)) { return {}; } Calendar *calendar = m_calendars.at(index.row()); switch (role) { case Name: return calendar->name; } return {}; } #include "moc_calendarlistmodel.cpp"