File indexing completed on 2024-04-28 07:44:53

0001 /*
0002     SPDX-FileCopyrightText: 2009 Stephen Kelly <steveire@gmail.com>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "modelselector.h"
0008 
0009 ModelSelector::ModelSelector(ProxyModelTest *parent)
0010     : ProxyModelTestData(parent)
0011     , m_model(nullptr)
0012     , m_selectionModel(nullptr)
0013     , m_rootModel(nullptr)
0014 {
0015     Q_ASSERT(parent);
0016 }
0017 
0018 void ModelSelector::setWatchedModel(QAbstractItemModel *model)
0019 {
0020     m_model = model;
0021     connect(m_model, &QObject::destroyed, this, &ModelSelector::modelDestroyed);
0022 }
0023 
0024 void ModelSelector::setSelectionModel(QItemSelectionModel *selectionModel)
0025 {
0026     if (selectionModel) {
0027         Q_ASSERT(!selectionModel->hasSelection());
0028     }
0029     m_selectionModel = selectionModel;
0030     connect(m_selectionModel, &QObject::destroyed, this, &ModelSelector::modelDestroyed);
0031 }
0032 
0033 void ModelSelector::setRootModel(DynamicTreeModel *rootModel)
0034 {
0035     m_rootModel = rootModel;
0036 }
0037 
0038 void ModelSelector::setWatch(bool watch)
0039 {
0040     if (!m_model) {
0041         return;
0042     }
0043 
0044     disconnect(m_model, &QAbstractItemModel::rowsInserted, this, &ModelSelector::rowsInserted);
0045     if (watch) {
0046         Q_ASSERT(m_model);
0047         connect(m_model, &QAbstractItemModel::rowsInserted, this, &ModelSelector::rowsInserted);
0048         if (m_model->hasChildren()) {
0049             rowsInserted(QModelIndex(), 0, m_model->rowCount() - 1);
0050         }
0051     }
0052 }
0053 
0054 void ModelSelector::rowsInserted(const QModelIndex &parent, int start, int end)
0055 {
0056     Q_ASSERT(end >= start);
0057     Q_ASSERT(m_selectionModel);
0058 
0059     int row = start;
0060     static const int column = 0;
0061     QModelIndex idx = m_model->index(row, column, parent);
0062 
0063     while (idx.isValid() && row <= end) {
0064         int item = idx.data().toInt();
0065         if (m_selectedRows.contains(item)) {
0066             m_selectionModel->select(idx, QItemSelectionModel::SelectCurrent);
0067         }
0068         if (m_model->hasChildren(idx)) {
0069             rowsInserted(idx, 0, m_model->rowCount(idx) - 1);
0070         }
0071         idx = idx.sibling(++row, column);
0072     }
0073 }
0074 
0075 #include "moc_modelselector.cpp"