src/model.cpp

changeset 173
8a3047468994
parent 159
1a04364d20b5
child 200
ca23936b455b
equal deleted inserted replaced
172:50f055543ff6 173:8a3047468994
99 * @param id Object id to look for 99 * @param id Object id to look for
100 * @return model index 100 * @return model index
101 */ 101 */
102 QModelIndex Model::find(ldraw::id_t id) const 102 QModelIndex Model::find(ldraw::id_t id) const
103 { 103 {
104 // FIXME: This linear search will probably cause performance issues 104 if (this->needObjectsByIdRebuild)
105 for (std::size_t i = 0; i < this->body.size(); i += 1) 105 {
106 { 106 this->objectsById.clear();
107 if (this->body[i]->id == id) 107 for (std::size_t i = 0; i < this->body.size(); ++i)
108 { 108 {
109 return this->index(static_cast<int>(i)); 109 this->objectsById[this->body[i]->id] = i;
110 } 110 }
111 } 111 this->needObjectsByIdRebuild = false;
112 return {}; 112 }
113 const auto it = this->objectsById.find(id);
114 if (it != this->objectsById.end())
115 {
116 return this->index(it->second);
117 }
118 else
119 {
120 return {};
121 }
113 } 122 }
114 123
115 /** 124 /**
116 * @brief Gets an object id by position in the model 125 * @brief Gets an object id by position in the model
117 * @param index Position of the object in the model 126 * @param index Position of the object in the model
157 const int position = static_cast<int>(this->body.size()); 166 const int position = static_cast<int>(this->body.size());
158 Q_EMIT this->beginInsertRows({}, position, position); 167 Q_EMIT this->beginInsertRows({}, position, position);
159 this->body.push_back(std::move(object)); 168 this->body.push_back(std::move(object));
160 Q_EMIT this->endInsertRows(); 169 Q_EMIT this->endInsertRows();
161 const ldraw::id_t id = this->body.back()->id; 170 const ldraw::id_t id = this->body.back()->id;
162 this->objectsById[id] = this->body.back().get(); 171 this->objectsById[id] = this->body.size() - 1;
163 return id; 172 return id;
164 } 173 }
165 174
166 /** 175 /**
167 * @brief Removes the object at the specified position 176 * @brief Removes the object at the specified position
171 { 180 {
172 if (position >= 0 and position < signed_cast(this->body.size())) 181 if (position >= 0 and position < signed_cast(this->body.size()))
173 { 182 {
174 Q_EMIT this->beginRemoveRows({}, position, position); 183 Q_EMIT this->beginRemoveRows({}, position, position);
175 this->body.erase(std::begin(this->body) + position); 184 this->body.erase(std::begin(this->body) + position);
185 this->needObjectsByIdRebuild = true;
176 Q_EMIT this->endRemoveRows(); 186 Q_EMIT this->endRemoveRows();
177 } 187 }
178 } 188 }
179 189
180 void Model::emitDataChangedSignal(int position) 190 void Model::emitDataChangedSignal(int position)

mercurial