1 #include "WordListModel.h"
3 WordListModel::WordListModel(QObject *parent) :
4 QAbstractListModel(parent)
6 QHash<int, QByteArray> roles;
7 roles[WordRole] = "word";
8 roles[IsBookmarkedRole] = "isBookmarked";
9 roles[NumberRole] = "number";
15 int WordListModel::rowCount(const QModelIndex &parent) const
17 return _wordList.count();
20 void WordListModel::addWord(QString word, QList<Translation *> translations, bool isBookmarked)
22 beginInsertRows(QModelIndex(), rowCount(), rowCount());
23 _translations.insert(word, translations);
25 _wordInBookmarks.insert(word, isBookmarked);
29 void WordListModel::clear()
32 if (!_wordList.isEmpty()){
36 _translations.clear();
37 _wordInBookmarks.clear();
44 QVariant WordListModel::data(const QModelIndex &index, int role) const
46 if (index.row() < 0 || index.row() > _translations.count()){
52 return _wordList[index.row()];
54 if (role == NumberRole){
57 if (role == IsBookmarkedRole){
58 return _wordInBookmarks[_wordList[index.row()]];
63 bool WordListModel::setData(const QModelIndex &index, const QVariant &value, int role)
65 int res = setDataPriv(index.row(), value, role);
73 Qt::ItemFlags WordListModel::flags(const QModelIndex &index) const
75 Qt::ItemFlags fl = QAbstractItemModel::flags(index);
76 return (fl | Qt::ItemIsEditable);
79 void WordListModel::setTranslations(QHash<QString, QList<Translation *> > translations, QHash<QString, bool> wordsInBookmarks)
81 QHashIterator<QString, QList<Translation *> > i(translations);
84 addWord(i.key(), i.value(), wordsInBookmarks[i.key()]);
91 void WordListModel::sort(int column, Qt::SortOrder order)
97 int right = _wordList.count() - 1;
100 if (order == Qt::AscendingOrder){
101 qSort(_wordList.begin(), _wordList.end());
102 } else if (order == Qt::DescendingOrder) {
103 qSort(_wordList.begin(), _wordList.end(), qGreater<QString>());
108 void WordListModel::setModelProperty(int index, const QVariant value, QString role)
110 if (role.contains("isBookmarked"))
112 setDataPriv(index, value, IsBookmarkedRole);
116 int WordListModel::setDataPriv(int index, const QVariant &value, int role)
118 bool bookmarksOnly = false;
119 if (_wordInBookmarks.values().count(false) == 0){
120 bookmarksOnly = true;
123 if (index < 0 || index > _translations.count())
126 QString word = _wordList[index];
127 if (role == WordRole)
129 if (role == NumberRole)
131 if (role == IsBookmarkedRole)
133 if (value.type() == QVariant::Bool)
135 _wordInBookmarks[word] = value.toBool();
136 Q_EMIT dataChanged(this->index(0), this->index(_translations.count() - 1));
137 if (_wordInBookmarks[word] == true){
138 Q_EMIT addToBookmarks(word);
140 Q_EMIT removeFromBookmarks(word);
141 if (bookmarksOnly == true){
142 beginRemoveRows(QModelIndex(), index, index + 1);
143 this->_translations.remove(_wordList[index]);
144 this->_wordInBookmarks.remove(_wordList[index]);
145 this->_wordList.removeAt(index);