#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QObject>
#include <QAbstractTableModel>
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit TableModel(QObject *parent = nullptr);
void setCell(const QVector<QVector<QString> > &cells);
protected:
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
QVector<QVector<QString>> _cells;
};
#endif // TABLEMODEL_H
#include "tablemodel.h"
#include "global.h"
TableModel::TableModel(QObject *parent) : QAbstractTableModel(parent)
{
//使用[]要先resize
_cells.resize(ROW_OF_TABLE);
for(int i=0;i<ROW_OF_TABLE;i++)
{
QVector<QString> vec(COLUMN_OF_TABLE);
_cells[i]=vec;
}
}
//resetModel()是更新数据的
void TableModel::setCell(const QVector<QVector<QString> >& cells)
{
beginResetModel();
_cells=cells;
endResetModel();
}
QVariant TableModel::data(const QModelIndex &index, int role) const
{
//Q_UNUSED(role);
if(role==Qt::DisplayRole)
{
int row=index.row();
int col=index.column();
return _cells[row][col];
}
else if (role == Qt::TextAlignmentRole)
{
return int(Qt::AlignHCenter | Qt::AlignVCenter);
}
return QVariant();//这挺重要,这个函数调用多次,用来显示数据的
}
//rowCount和columnCount必须重写
int TableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return ROW_OF_TABLE;
}
int TableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return COLUMN_OF_TABLE;
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation==Qt::Horizontal && role==Qt::DisplayRole)
{
switch (section) {
case 0:
return "ID";
break;
case 1:
return "SA";
break;
case 2:
return "状态";
break;
case 3:
return "进度";
break;
case 4:
return "错误";
break;
case 5:
return "时间";
break;
default:
break;
}
}
else if(orientation==Qt::Horizontal && role==Qt::TextAlignmentRole)
{
return int(Qt::AlignHCenter | Qt::AlignVCenter);
}
return QVariant();
}
setData()没用到,不过应该是View->Data,对应data()是Data->View
结合QTableView就可以了
model=new TableModel(this);
view=new QTableView(this);
view->setModel(model);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
view->verticalHeader()->setVisible(false);