程序运行截图如下:
代码如下:
mymodel.h
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractTableModel>
#include <QVector>
#include <QMap>
#include <QStringList>
class MyModel:public QAbstractTableModel
{
Q_OBJECT
public:
MyModel(QObject *parent=0);
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
QVector<short> m_department;
QVector<short> m_peopleName;
QMap<short,QString> m_departmentMap;
QMap<short,QString> m_m_peopleNameMap;
QStringList m_pay;
QStringList m_header;
void populateModel();
};
#endif // MYMODEL_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class MyModel;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
MyModel *m_myModel;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
mymodel.cpp
#include "mymodel.h"
#include <QDebug>
MyModel::MyModel(QObject *parent):
QAbstractTableModel(parent)
{
m_departmentMap[1]=tr("开发部");
m_departmentMap[2]=tr("运维部");
m_departmentMap[3]=tr("销售部");
m_departmentMap[4]=tr("售后部");
m_m_peopleNameMap[1]=tr("猪小明");
m_m_peopleNameMap[2]=tr("闰土");
m_m_peopleNameMap[3]=tr("锅盖");
m_m_peopleNameMap[4]=tr("米线");
m_m_peopleNameMap[5]=tr("妹爷");
m_m_peopleNameMap[6]=tr("球球");
m_m_peopleNameMap[7]=tr("腿腿");
m_m_peopleNameMap[8]=tr("小美");
populateModel();
}
void MyModel::populateModel()
{
m_header<<tr("部门")<<tr("员工名")<<tr("薪资");
m_department<<1<<2<<3<<4<<2<<4<<3<<1;
m_peopleName<<1<<3<<5<<7<<4<<8<<6<<2;
m_pay<<tr("8000")<<tr("6000")<<tr("5000")<<tr("9000")<<tr("13000")<<tr("18000")<<tr("26000")<<tr("8500");
}
int MyModel::columnCount(const QModelIndex &parent) const{
Q_UNUSED(parent)
return 3;
}
int MyModel::rowCount(const QModelIndex &parent) const{
Q_UNUSED(parent)
return m_department.size();
}
QVariant MyModel::data(const QModelIndex &index, int role) const{
if(!index.isValid())
return QVariant();
if(role==Qt::DisplayRole){
switch(index.column())
{
case 0:
return m_departmentMap[m_department[index.row()]];
break;
case 1:
return m_m_peopleNameMap[m_peopleName[index.row()]];
break;
case 2:
return m_pay[index.row()];
default:
return QVariant();
}
}
return QVariant();
}
QVariant MyModel::headerData(int section, Qt::Orientation orientation, int role) const{
if(role==Qt::DisplayRole&&orientation==Qt::Horizontal)
return m_header[section];
return QAbstractTableModel::headerData(section,orientation,role);
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "mymodel.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_myModel=new MyModel;
ui->tableView->setModel(m_myModel);
}
Widget::~Widget()
{
delete ui;
}