| 1 |
/* |
| 2 |
* Copyright (C) 2018 Aetf <[email protected]> |
| 3 |
* |
| 4 |
* This program is free software: you can redistribute it and/or modify |
| 5 |
* it under the terms of the GNU General Public License as published by |
| 6 |
* the Free Software Foundation, either version 2 or (at your option) |
| 7 |
* version 3 of the License. |
| 8 |
* |
| 9 |
* This program is distributed in the hope that it will be useful, |
| 10 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
* GNU General Public License for more details. |
| 13 |
* |
| 14 |
* You should have received a copy of the GNU General Public License |
| 15 |
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
*/ |
| 17 |
|
| 18 |
#include <QAbstractItemView> |
| 19 |
#include <QStyledItemDelegate> |
| 20 |
|
| 21 |
#include <functional> |
| 22 |
|
| 23 |
namespace |
| 24 |
{ |
| 25 |
class WidgetItemDelegate : public QStyledItemDelegate |
| 26 |
{ |
| 27 |
std::function<QWidget*(QWidget*, const QModelIndex&)> m_create; |
| 28 |
|
| 29 |
public: |
| 30 |
explicit WidgetItemDelegate(QObject* parent, std::function<QWidget*(QWidget*, const QModelIndex&)>&& create) |
| 31 |
: QStyledItemDelegate(parent) |
| 32 |
, m_create(std::move(create)) |
| 33 |
{ |
| 34 |
} |
| 35 |
|
| 36 |
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex& index) const override |
| 37 |
{ |
| 38 |
if (!index.isValid()) |
| 39 |
return nullptr; |
| 40 |
return m_create(parent, index); |
| 41 |
} |
| 42 |
}; |
| 43 |
} // namespace |
| 44 |
|
| 45 |
void installWidgetItemDelegate(QAbstractItemView* view, |
| 46 |
int column, |
| 47 |
std::function<QWidget*(QWidget*, const QModelIndex&)>&& create) |
| 48 |
{ |
| 49 |
auto delegate = new WidgetItemDelegate(view, std::move(create)); |
| 50 |
// doesn't take ownership |
| 51 |
view->setItemDelegateForColumn(column, delegate); |
| 52 |
|
| 53 |
for (int row = 0; row != view->model()->rowCount({}); ++row) { |
| 54 |
view->openPersistentEditor(view->model()->index(row, column)); |
| 55 |
} |
| 56 |
QObject::connect(view->model(), |
| 57 |
&QAbstractItemModel::rowsInserted, |
| 58 |
delegate, |
| 59 |
[view, column](const QModelIndex&, int first, int last) { |
| 60 |
for (int i = first; i <= last; ++i) { |
| 61 |
auto idx = view->model()->index(i, column); |
| 62 |
view->openPersistentEditor(idx); |
| 63 |
} |
| 64 |
}); |
| 65 |
} |