AlbumModel.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "AlbumModel.h"
  2. using namespace std;
  3. AlbumModel::AlbumModel(QObject* parent)
  4. : QAbstractListModel(parent),
  5. mDb(DatabaseManager::instance()),
  6. mAlbums(mDb.albumDao.albums()) {}
  7. QModelIndex AlbumModel::addAlbum(const Album& album) {
  8. int rowIndex = rowCount();
  9. beginInsertRows(QModelIndex(), rowIndex, rowIndex);
  10. unique_ptr<Album> newAlbum(new Album(album));
  11. mDb.albumDao.addAlbum(*newAlbum);
  12. mAlbums->push_back(std::move(newAlbum));
  13. endInsertRows();
  14. return index(rowIndex, 0);
  15. }
  16. int AlbumModel::rowCount(const QModelIndex& parent) const {
  17. return mAlbums->size();
  18. }
  19. QVariant AlbumModel::data(const QModelIndex& index, int role) const {
  20. if (!isIndexValid(index)) {
  21. return QVariant();
  22. }
  23. const Album& album = *mAlbums->at(index.row());
  24. switch (role) {
  25. case Roles::IdRole:
  26. return album.id();
  27. case Roles::NameRole:
  28. case Qt::DisplayRole:
  29. return album.name();
  30. default:
  31. return QVariant();
  32. }
  33. }
  34. bool AlbumModel::setData(const QModelIndex& index,
  35. const QVariant& value,
  36. int role) {
  37. if (!isIndexValid(index) || role != Roles::NameRole) {
  38. return false;
  39. }
  40. Album& album = *mAlbums->at(index.row());
  41. album.setName(value.toString());
  42. mDb.albumDao.updateAlbum(album);
  43. emit dataChanged(index, index);
  44. return true;
  45. }
  46. bool AlbumModel::removeRows(int row, int count, const QModelIndex& parent) {
  47. if (row < 0 || row >= rowCount() || count < 0 || (row + count) > rowCount()) {
  48. return false;
  49. }
  50. beginRemoveRows(parent, row, row + count - 1);
  51. int countLeft = count;
  52. while (countLeft--) {
  53. const Album& album = *mAlbums->at(row + countLeft);
  54. mDb.albumDao.removeAlbum(album.id());
  55. }
  56. mAlbums->erase(mAlbums->begin() + row, mAlbums->begin() + row + count);
  57. endRemoveRows();
  58. return true;
  59. }
  60. QHash<int, QByteArray> AlbumModel::roleNames() const {
  61. QHash<int, QByteArray> roles;
  62. ;
  63. roles[Roles::IdRole] = "id";
  64. roles[Roles::NameRole] = "name";
  65. return roles;
  66. }
  67. bool AlbumModel::isIndexValid(const QModelIndex& index) const {
  68. if (index.row() < 0 || index.row() >= rowCount() || !index.isValid()) {
  69. return false;
  70. }
  71. return true;
  72. }