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";
11 isBookmarkModeActive = false;
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();
42 isBookmarkModeActive = false;
45 QVariant WordListModel::data(const QModelIndex &index, int role) const
47 if (index.row() < 0 || index.row() > _translations.count()){
53 return _wordList[index.row()];
55 if (role == NumberRole){
58 if (role == IsBookmarkedRole){
59 return _wordInBookmarks[_wordList[index.row()]];
64 bool WordListModel::setData(const QModelIndex &index, const QVariant &value, int role)
66 int res = setDataPriv(index.row(), value, role);
74 Qt::ItemFlags WordListModel::flags(const QModelIndex &index) const
76 Qt::ItemFlags fl = QAbstractItemModel::flags(index);
77 return (fl | Qt::ItemIsEditable);
80 void WordListModel::setTranslations(QHash<QString, QList<Translation *> > translations, QHash<QString, bool> wordsInBookmarks)
82 QHashIterator<QString, QList<Translation *> > i(translations);
85 addWord(i.key(), i.value(), wordsInBookmarks[i.key()]);
92 void WordListModel::sort(int column, Qt::SortOrder order)
98 int right = _wordList.count() - 1;
101 if (order == Qt::AscendingOrder){
102 qSort(_wordList.begin(), _wordList.end());
103 } else if (order == Qt::DescendingOrder) {
104 qSort(_wordList.begin(), _wordList.end(), qGreater<QString>());
109 void WordListModel::setModelProperty(int index, const QVariant value, QString role)
111 if (role.contains("isBookmarked"))
113 setDataPriv(index, value, IsBookmarkedRole);
117 int WordListModel::setDataPriv(int index, const QVariant &value, int role)
119 if (index < 0 || index > _translations.count() - 1)
122 QString word = _wordList[index];
123 if (role == WordRole)
125 if (role == NumberRole)
127 if (role == IsBookmarkedRole)
129 if (value.type() == QVariant::Bool)
131 _wordInBookmarks[word] = value.toBool();
132 if (_wordInBookmarks[word] == true){
133 Q_EMIT addToBookmarks(word);
135 Q_EMIT removeFromBookmarks(word);
136 if (isBookmarkModeActive == true){
137 beginRemoveRows(QModelIndex(), index, index + 1);
138 this->_translations.remove(_wordList[index]);
139 this->_wordInBookmarks.remove(_wordList[index]);
140 this->_wordList.removeAt(index);
144 Q_EMIT dataChanged(this->index(0), this->index(_translations.count() - 1));
155 void WordListModel::setBookmarkModeActive(bool mode)
157 isBookmarkModeActive = mode;