知识点
virtual int rowCount(const QModelIndex& parent =QModelIndex())const;
virtual int columnCount(const QModelIndex& parent =QModelIndex())const;
QVariant data(const QModelIndex& index,int role)const;
QVariant headerData(int section,Qt::Orientation orientation,int role)const;
view.setModel(&modelEx);设置模型
modelex
modelex.h
#ifndef MODELEX_H
#define MODELEX_H
#include <QAbstractTableModel>
#include <QVector>
#include <QMap>
#include <QStringList>
class ModelEx : public QAbstractTableModel
{
public:
explicit ModelEx(QObject *parent = 0);
virtual int rowCount(const QModelIndex& parent =QModelIndex())const;
virtual int columnCount(const QModelIndex& parent =QModelIndex())const;
QVariant data(const QModelIndex& index,int role)const;
QVariant headerData(int section,Qt::Orientation orientation,int role)const;
signals:
public slots:
private:
QVector<short> army;
QVector<short> weaponType;
QMap<short,QString>armyMap;
QMap<short,QString>weaponTypeMap;
QStringList weapon;
QStringList header;
void populateModel();
};
#endif
modelex.cpp
#include "modelex.h"
ModelEx::ModelEx(QObject *parent):QAbstractTableModel(parent)
{
armyMap[1] = tr("空军");
armyMap[2] = tr("海军");
armyMap[3] = tr("陆军");
armyMap[4] = tr("海军和陆军");
armyMap[5] = tr("海军和陆军2");
weaponTypeMap[1] = tr("轰炸机");
weaponTypeMap[2] = tr("战斗机");
weaponTypeMap[3] = tr("坦克");
weaponTypeMap[4] = tr("飞机");
weaponTypeMap[5] = tr("炮弹");
weaponTypeMap[6] = tr("舰艇");
populateModel();
}
int ModelEx::rowCount(const QModelIndex &parent) const
{
return army.size();
}
int ModelEx::columnCount(const QModelIndex &parent) const
{
return 4;
}
QVariant ModelEx::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
{
return QVariant();
}
if(role ==Qt::DisplayRole)
{
switch (index.column()) {
case 0:
return armyMap[army[index.row()]];
break;
case 1:
return weaponTypeMap[weaponType[index.row()]];
break;
case 2:
return weapon[index.row()];
break;
case 3:
return weapon[index.row()];
break;
default:
return QVariant();
}
}
return QVariant();
}
QVariant ModelEx::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role ==Qt::DisplayRole && orientation ==Qt::Horizontal)
{
return header[section];
}
return QAbstractTableModel::headerData(section,orientation,role);
}
void ModelEx::populateModel()
{
header<<tr("军种")<<tr("种类")<<tr("武器")<<tr("武器1");
army<<1<<2<<3<<4<<2<<4<<3<<1;
weaponType<<1<<3<<5<<6<<2<<5<<2<<5;
weapon<<tr("B-2")<<tr("普通")<<tr("特殊")<<tr("高级")<<tr("困难")<<tr("复杂")<<tr("困难2")<<tr("复杂2");
}
main.cpp
#include "modelex.h"
#include <QApplication>
#include <QTableView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ModelEx modelEx;
QTableView view;
view.setModel(&modelEx);
view.setWindowTitle(QObject::tr("使用模型"));
view.resize(400,400);
view.show();
return a.exec();
}
运行图