File indexing completed on 2024-05-12 16:34:29

0001 /* This file is part of the KDE project
0002 * Copyright (c) 2010 Jan Hambrecht <jaham@gmx.net>
0003 *
0004 * This library is free software; you can redistribute it and/or
0005 * modify it under the terms of the GNU Lesser General Public
0006 * License as published by the Free Software Foundation; either
0007 * version 2.1 of the License, or (at your option) any later version.
0008 *
0009 * This library is distributed in the hope that it will be useful,
0010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
0011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0012 * Library General Public License for more details.
0013 *
0014 * You should have received a copy of the GNU Lesser General Public License
0015 * along with this library; see the file COPYING.LIB.  If not, write to
0016 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0017 * Boston, MA 02110-1301, USA.
0018 */
0019 
0020 #include "MatrixDataModel.h"
0021 
0022 MatrixDataModel::MatrixDataModel(QObject *parent)
0023     : QAbstractTableModel(parent)
0024     , m_rows(0), m_cols(0)
0025 {
0026 }
0027 
0028 void MatrixDataModel::setMatrix(const QVector<qreal> &matrix, int rows, int cols)
0029 {
0030     m_matrix = matrix;
0031     m_rows = rows;
0032     m_cols = cols;
0033     Q_ASSERT(m_rows);
0034     Q_ASSERT(m_cols);
0035     Q_ASSERT(m_matrix.count() == m_rows*m_cols);
0036     reset();
0037 }
0038 
0039 QVector<qreal> MatrixDataModel::matrix() const
0040 {
0041     return m_matrix;
0042 }
0043 
0044 int MatrixDataModel::rowCount(const QModelIndex &/*parent*/) const
0045 {
0046     return m_rows;
0047 }
0048 
0049 int MatrixDataModel::columnCount(const QModelIndex &/*parent*/) const
0050 {
0051     return m_cols;
0052 }
0053 
0054 QVariant MatrixDataModel::data(const QModelIndex &index, int role) const
0055 {
0056     int element = index.row() * m_cols + index.column();
0057     switch(role) {
0058         case Qt::DisplayRole:
0059         case Qt::EditRole:
0060             return QVariant(QString("%1").arg(m_matrix[element], 2));
0061             break;
0062         default:
0063             return QVariant();
0064     }
0065 }
0066 
0067 bool MatrixDataModel::setData(const QModelIndex &index, const QVariant &value, int /*role*/)
0068 {
0069     int element = index.row() * m_cols + index.column();
0070     bool valid = false;
0071     qreal elementValue = value.toDouble(&valid);
0072     if (!valid)
0073         return false;
0074     m_matrix[element] = elementValue;
0075     emit dataChanged(index, index);
0076     return true;
0077 }
0078 
0079 Qt::ItemFlags MatrixDataModel::flags(const QModelIndex &/*index*/) const
0080 {
0081     return Qt::ItemIsEnabled|Qt::ItemIsSelectable|Qt::ItemIsEditable;
0082 }