- modellex.h
1 #ifndef MODELEX_H 2 #define MODELEX_H 3 #include <QAbstractItemModel> 4 #include <QVector> 5 #include <QMap> 6 #include <QStringList> 7 #include <QWidget> 8 9 10 class modelex : public QAbstractTableModel 11 { 12 13 public: 14 explicit modelex(QObject *parent = 0); 15 16 virtual int rowCount(const QModelIndex &parent=QModelIndex()) const; 17 virtual int columnCount(const QModelIndex &parent=QModelIndex()) const; 18 QVariant data(const QModelIndex &index, int role) const; 19 QVariant headerData(int section, Qt::Orientation orientation, int role) const; 20 21 private: 22 QVector<int> army; 23 QVector<int> weapon; 24 QMap<int,QString> armymap; 25 QMap<int,QString> weaponmap; 26 27 QStringList weaponlist; 28 QStringList armylist; 29 QStringList header; 30 31 void showModel(); 32 }; 33 34 #endif // MODELEX_H
- modelex.cpp
1 #include "modelex.h" 2 3 modelex::modelex(QObject *parent):QAbstractTableModel(parent) 4 { 5 armymap[1] ="空军"; 6 armymap[2] ="海军"; 7 armymap[3] ="陆军"; 8 9 weaponmap[1] = "AK47"; 10 weaponmap[2] = "M16"; 11 weaponmap[3] = "M18"; 12 showModel(); 13 } 14 15 int modelex::rowCount(const QModelIndex &parent) const 16 { 17 return army.size();//行数 18 } 19 20 int modelex::columnCount(const QModelIndex &parent) const 21 { 22 return 2;//列数 23 } 24 25 //返回每一行每一列的数据 26 QVariant modelex::data(const QModelIndex &index, int role) const 27 { 28 if(!index.isValid()) 29 { 30 return QVariant(); 31 } 32 if(role == Qt::DisplayRole) 33 { 34 switch(index.column()) 35 { 36 case 0: 37 return armymap[army[index.row()]]; 38 break; 39 case 1: 40 return armymap[weapon[index.row()]]; 41 break; 42 default: 43 return QVariant(); 44 } 45 46 } 47 return QVariant(); 48 } 49 50 QVariant modelex::headerData(int section, Qt::Orientation orientation, int role) const 51 { 52 if(role == Qt::DisplayRole && Qt::Horizontal == orientation) 53 { 54 //返回表的开头 55 return header[section]; 56 } 57 else 58 { 59 return QAbstractTableModel::headerData(section,orientation,role); 60 } 61 } 62 63 void modelex::showModel() 64 { 65 header<<"兵种" <<"兵器"; 66 //数字与字符串对应 67 army<<1<<2<<3<<2<<1; 68 weapon<<1<<2<<3<<2<<1; 69 }
- main.cpp
1 #include "widget.h" 2 #include <QApplication> 3 #include <QTableView> 4 #include "modelex.h" 5 6 int main(int argc, char *argv[]) 7 { 8 QApplication a(argc, argv); 9 //Widget w; 10 //w.show(); 11 modelex m; 12 QTableView view; 13 view.setModel(&m); 14 view.show(); 15 view.resize(800,600); 16 17 return a.exec(); 18 }
运行效果