Skip to content

Instantly share code, notes, and snippets.

@andr1972
Created March 9, 2019 17:41
Show Gist options
  • Save andr1972/a953f6019c6694dfe66451adcfc29914 to your computer and use it in GitHub Desktop.
Save andr1972/a953f6019c6694dfe66451adcfc29914 to your computer and use it in GitHub Desktop.
#pragma once
#include <QString>
#include <QAbstractTableModel>
#include "ivariantable.h"
template <class T>
class TableModel : public QAbstractTableModel
{
private:
QVector<T*> variantableList;
QStringList headerList;
public:
explicit TableModel(QObject *parent): QAbstractTableModel(parent){}
virtual ~TableModel() override{}
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override
{
Q_UNUSED(orientation);
if (role != Qt::DisplayRole)
return QVariant();
if (orientation==Qt::Orientation::Horizontal)
{
return QVariant(headerList[section]);
}
else
return QString::number(section);
}
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override
{
if(hasIndex(row, column, parent) == false) {
return QModelIndex();
}
return createIndex(row, column, nullptr);
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override
{
return variantableList.count();
}
int columnCount(const QModelIndex &parent = QModelIndex()) const override
{
Q_UNUSED(parent)
return headerList.count();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
{
if(!index.isValid())
return QVariant();
if(role != Qt::DisplayRole)
return QVariant();
return variantableList[index.row()]->getData(index.column());
}
Qt::ItemFlags flags(const QModelIndex& index) const override
{
if (!index.isValid())
return Qt::NoItemFlags;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
void setList(QVector<T*> &variantableList, QStringList &headerList)
{
this->variantableList = variantableList;
this->headerList = headerList;
}
};
#pragma once
#include <QVariant>
struct IVariantable
{
virtual ~IVariantable() {}
virtual QVariant getData(int col) = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment