13.5.  Smarter Pointers

[ fromfile: smarterpointers.xml id: smarterpointers ]

Example 13.24. src/libs/dataobjects/dataobjecttablemodel.h

[ . . . . ]

class DOBJS_EXPORT DataObjectTableModel : public QAbstractTableModel {
    Q_OBJECT
  public:
    explicit DataObjectTableModel(DataObject* headerModel = 0, 
                                  QObject* parent=0);
    virtual bool insertRecord(QSharedPointer<DataObject> newRecord,
                              int position = -1,
                              const QModelIndex& = QModelIndex());
    QStringList toStringList() const;

    QString toString() const;

    virtual int fieldIndex(const QString& fieldName) const;
    virtual ~DataObjectTableModel();
[ . . . . ]

  public slots:
    void clear();
    void rowChanged(const QString& fileName);

  protected:
    QList<QSharedPointer<DataObject> > m_Data;
    QList<bool> m_isEditable;
    QStringList m_Headers;
    DataObject* m_Original;
    void extractHeaders(DataObject* hmodel);
  public:
    DataObjectTableModel& operator<<(QSharedPointer<DataObject> newObj) {
        insertRecord(newObj);
        return *this;
    }
};

Example 13.25. src/libs/dataobjects/dataobjecttablemodel.cpp

[ . . . . ]

QVariant DataObjectTableModel::
data(const QModelIndex& index, int role) const {
    if (!index.isValid())
        return QVariant();
    int row(index.row()), col(index.column());
    if (row >= rowCount()) return QVariant();
    QSharedPointer<DataObject> lineItem(m_Data.at(row));
    if (lineItem.isNull()) {
        qDebug() << "lineitem=0:" << index;
        return QVariant();
    }
    if (role == Qt::UserRole || role == Qt::ToolTipRole)
        return lineItem->objectName();
    else if (role == DisplayRole || role == EditRole) {
        return lineItem->property(m_Headers.at(col));
    } else
        return QVariant();
}


bool DataObjectTableModel::
setData(const QModelIndex& index, const QVariant& value, int role) {
    if (index.isValid() && role == EditRole) {
        int row(index.row()), col(index.column());
        QSharedPointer<DataObject> lineItem(m_Data.at(row));
        lineItem->setProperty(m_Headers.at(col), value);
        emit dataChanged(index, index);
        return true;
    }
    return false;
}