/* * Copyright (C) 2011, 2013 Canonical, Ltd. * * Authors: * Florian Boucault * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef LISTMODELWRAPPER_H #define LISTMODELWRAPPER_H // Qt #include #include #include #include template class ListModelWrapper : public QAbstractListModel { public: explicit ListModelWrapper(const std::vector& list, sigc::signal itemAddedSignal, sigc::signal itemRemovedSignal, QObject *parent = nullptr); ~ListModelWrapper(); QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; int rowCount(const QModelIndex& parent = QModelIndex()) const; const QList& rawList() const; private: void onItemAdded(ItemClass item); void onItemRemoved(ItemClass item); void onItemChanged(ItemClass item); QList m_list; QMap m_indexes; void addItem(ItemClass item, int index); void removeItem(ItemClass item, int index); }; template ListModelWrapper::ListModelWrapper(const std::vector& list, sigc::signal itemAddedSignal, sigc::signal itemRemovedSignal, QObject *parent) : QAbstractListModel(parent) { for (unsigned int i=0; i ListModelWrapper::~ListModelWrapper() { m_indexes.clear(); while (!m_list.isEmpty()) { delete m_list.takeFirst(); } } template int ListModelWrapper::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent) return m_list.count(); } template const QList& ListModelWrapper::rawList() const { return m_list; } template QVariant ListModelWrapper::data(const QModelIndex& index, int) const { if (!index.isValid()) { return QVariant(); } WrapperItem* item = m_list.at(index.row()); return QVariant::fromValue(item); } template void ListModelWrapper::onItemAdded(ItemClass item) { int index = m_list.count(); beginInsertRows(QModelIndex(), index, index); addItem(item, index); endInsertRows(); } template void ListModelWrapper::onItemRemoved(ItemClass item) { int index = m_indexes[item]; beginInsertRows(QModelIndex(), index, index); removeItem(item, index); endInsertRows(); } template void ListModelWrapper::onItemChanged(ItemClass item) { QModelIndex itemIndex = index(m_indexes[item]); Q_EMIT dataChanged(itemIndex, itemIndex); } template void ListModelWrapper::addItem(ItemClass item, int index) { m_indexes.insert(item, index); m_list.insert(index, new WrapperItem(item)); } template void ListModelWrapper::removeItem(ItemClass item, int index) { m_indexes.remove(item); delete m_list.takeAt(index); } #endif // LISTMODELWRAPPER_H