Пытаюсь описать модель-таблицу.
Вот код
C++ (Qt)
class TableModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit TableModel(QList<ElementModel *> *elements, QObject *parent = 0);
virtual ~TableModel();
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent) const;
QModelIndex parent(const QModelIndex &child) const;
void setList(QList<ElementModel*> *);
private:
QList<ElementModel*> *list;
enum Column{
SURNAME = 0,
NAME,
LAST
};
};
TableModel::TableModel(QList<ElementModel *> *elements, QObject *parent) :
QAbstractItemModel(parent)
{
list = elements;
}
TableModel::~TableModel()
{
}
int TableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return list->count();
}
int TableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return LAST;
}
QVariant TableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid() ||
list->count() <= index.row() ||
(role != Qt::DisplayRole && role != Qt::EditRole))
return QVariant();
switch(index.column()){
case 0: return list->at(index.row())->surname;
case 1: return list->at(index.row())->name;
}
return QVariant();
}
bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
}
QModelIndex TableModel::parent(const QModelIndex &child) const
{
return QModelIndex();
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role != Qt::DisplayRole)
return QVariant();
if(orientation == Qt::Vertical)
return section;
switch(section){
case SURNAME:
return "Surname";
case NAME:
return "Name";
}
return QVariant();
}
QModelIndex TableModel::index(int row, int column, const QModelIndex &parent) const
{
if(!hasIndex(row,column,parent))
return QModelIndex();
return createIndex(row,column,parent.internalPointer());
}
void TableModel::setList(QList<ElementModel*> *elements)
{
beginResetModel();
list = elements;
endResetModel();
}
C++ (Qt)
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ElementModel *one = new ElementModel();
one->surname = "IVANOV";
one->name = "IVAN";
ElementModel *two = new ElementModel();
two->surname = "PETROW";
two->name = "PETR";
QList<ElementModel*> list;
list.append(one);
list.append(two);
tableModel = new TableModel(&list);
ui->tableView->setModel(tableModel);
}
C++ (Qt)
class ElementModel : public QObject
{
Q_OBJECT
public:
explicit ElementModel(QObject *parent = 0);
virtual ~ElementModel();
public:
QString surname;
QString name;
};
Но таблица не заполняется???
Не могу понять почему???