File indexing completed on 2024-05-12 16:23:39
0001 /* 0002 * SPDX-FileCopyrightText: 2021 Dimitris Kardarakos <dimkard@posteo.net> 0003 * 0004 * SPDX-License-Identifier: GPL-3.0-or-later 0005 */ 0006 0007 #include "feedgroupsmodel.h" 0008 #include "database.h" 0009 #include <QSqlQuery> 0010 0011 FeedGroupsModel::FeedGroupsModel(QObject *parent) 0012 : QAbstractListModel{parent} 0013 , m_feed_groups{} 0014 { 0015 loadFromDatabase(); 0016 0017 connect(&Database::instance(), &Database::feedGroupsUpdated, [this]() { 0018 loadFromDatabase(); 0019 }); 0020 0021 connect(&Database::instance(), &Database::feedGroupRemoved, [this]() { 0022 loadFromDatabase(); 0023 }); 0024 } 0025 0026 QHash<int, QByteArray> FeedGroupsModel::roleNames() const 0027 { 0028 return {{GroupName, "name"}, {GroupDescription, "description"}, {IsDefault, "isDefault"}}; 0029 } 0030 0031 int FeedGroupsModel::rowCount(const QModelIndex &parent) const 0032 { 0033 if (parent.isValid()) { 0034 return 0; 0035 } 0036 0037 return m_feed_groups.count(); 0038 } 0039 0040 QVariant FeedGroupsModel::data(const QModelIndex &index, int role) const 0041 { 0042 if (!index.isValid()) { 0043 return QVariant(); 0044 } 0045 0046 auto row = index.row(); 0047 0048 switch (role) { 0049 case GroupName: { 0050 return m_feed_groups.at(row).name; 0051 } 0052 case GroupDescription: { 0053 return m_feed_groups.at(row).description; 0054 } 0055 case IsDefault: 0056 return m_feed_groups.at(row).isDefault; 0057 } 0058 0059 return QVariant(); 0060 } 0061 0062 void FeedGroupsModel::loadFromDatabase() 0063 { 0064 beginResetModel(); 0065 0066 m_feed_groups = {}; 0067 QSqlQuery q; 0068 if (q.prepare(QStringLiteral("SELECT * FROM FeedGroups;"))) { 0069 Database::instance().execute(q); 0070 while (q.next()) { 0071 FeedGroup group{}; 0072 group.name = q.value(QStringLiteral("name")).toString(); 0073 group.description = q.value(QStringLiteral("description")).toString(); 0074 group.isDefault = (q.value(QStringLiteral("defaultGroup")).toInt() == 1); 0075 m_feed_groups << group; 0076 } 0077 } 0078 0079 endResetModel(); 0080 }