#ifndef ODBTABLEMODEL_H #define ODBTABLEMODEL_H #include #include #include #include #include "define.h" #include "core_global.h" template class AutoTableModel : public QAbstractTableModel { public: explicit AutoTableModel(QObject *parent = NULL) :QAbstractTableModel(parent) { } virtual ~AutoTableModel() {} // QAbstractItemModel interface public: int rowCount(const QModelIndex &parent = QModelIndex()) const { Q_UNUSED(parent) return m_list.size(); } int columnCount(const QModelIndex &parent = QModelIndex()) const { Q_UNUSED(parent) if (m_list.isEmpty()) { return 0; } QSharedPointer entity = m_list.at(0); QObject *rawEntity = (QObject*)entity.data(); return rawEntity->metaObject()->propertyCount() - 1; } QVariant data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { QSharedPointer entity = m_list.at(index.row()); QObject *rawEntity = (QObject*)entity.data(); return rawEntity->property(rawEntity->metaObject()->property(index.column() + 1).name()); } return QVariant::Invalid; } QList > list() { return m_list; } QVariant headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) { return QVariant(); } if (orientation == Qt::Horizontal) { QObject *entity = (QObject*)new T(); for (int i = 0; i < entity->metaObject()->propertyCount(); i++) { if (i == section) { QString colName(entity->metaObject()->property(i + 1).name()); return tr(colName.toStdString().c_str()); } } delete entity; } return QVariant(section + 1); } virtual void sort(int column, Qt::SortOrder order) { if (m_list.isEmpty()) { return; } beginResetModel(); QObject *rawEntity = (QObject*)m_list.at(0).data(); const char *prop = rawEntity->metaObject()->property(column + 1).name(); std::sort(ALL(m_list), [prop, order](QSharedPointer entA, QSharedPointer entB) -> bool { if (order == Qt::AscendingOrder) { return ((QObject*)entA.data())->property(prop) < ((QObject*)entB.data())->property(prop); } else { return ((QObject*)entB.data())->property(prop) < ((QObject*)entA.data())->property(prop); } }); endResetModel(); } /*///////////////////////*/ QSharedPointer itemFromIndex(const QModelIndex &index) const { return m_list.at(index.row()); } void setItemToIndex(const QModelIndex &index, QSharedPointer data) { m_list.removeAt(index.row()); m_list.insert(index.row(), data); emit dataChanged(index, index); } void addRow(QSharedPointer data) { beginInsertRows(QModelIndex(), rowCount() - 1, rowCount() - 1); insertRow(rowCount()); m_list.append(data); endInsertRows(); } void removeRowAt(const QModelIndex &index) { beginRemoveRows(QModelIndex(), index.row(), index.row()); removeRow(index.row()); m_list.removeAt(index.row()); endRemoveRows(); } void setData(QList > list) { m_list = list; } private: QList > m_list; }; #endif // ODBTABLEMODEL_H