表格视图D
Posted Respect@
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表格视图D相关的知识,希望对你有一定的参考价值。
表格视图
表格视图
weap.h
#ifndef WEAPONMODEL_H
#define WEAPONMODEL_H
#include <QAbstractTableModel>
class WeaponModel : public QAbstractTableModel
{
public:
WeaponModel(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;
private:
QVector<short> army; //军队
QVector<short> weaponType; //武器类型
QMap<short,QString> armyMap; //军队映射
QMap<short,QString> weaponMap; //武器映射
QStringList weapon; //武器
QStringList header; //表头
void populateModel(); //表格数据的初始化
};
#endif // WEAPONMODEL_H
weap.cpp
#include "weaponmodel.h"
WeaponModel::WeaponModel(QObject* parent)
:QAbstractTableModel(parent)
{
armyMap[1] = QString("空军");
armyMap[2] = QString("海军");
armyMap[3] = QString("陆军");
armyMap[4] = QString("海军陆战队");
weaponMap[1] = QString("轰炸机");
weaponMap[2] = QString("战斗机");
weaponMap[3] = QString("航空母舰");
weaponMap[4] = QString("驱逐舰");
weaponMap[5] = QString("直升机");
weaponMap[6] = QString("坦克");
weaponMap[7] = QString("两栖攻击舰");
weaponMap[8] = QString("两栖战车");
populateModel();
}
int WeaponModel::rowCount(const QModelIndex &parent) const
{
return army.size();
}
int WeaponModel::columnCount(const QModelIndex &parent) const
{
return 3;
}
//放回指定索引的数据,将数值映射成文字
QVariant WeaponModel::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 weaponMap[weaponType[index.row()]];
break;
case 2:
return weapon[index.row()];
default:
return QVariant();
}
}
return QVariant();
}
QVariant WeaponModel::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 WeaponModel::populateModel()
{
header << QString("军种")
<< QString("种类")
<< QString("武器");
army << 1 << 2 << 3 << 4 << 2 << 4 << 3 << 1;
weaponType << 1 << 3 << 5 << 7 << 4 << 8 << 6 << 2;
weapon << QString("B-2") << QString("尼尔兹极")
<< QString("阿帕奇") << QString("黄蜂级")
<< QString("比例伯克级") << QString("AAAV")
<< QString("M1A1") << QString("F-22");
}
main.cpp
#include <QApplication>
#include "weaponmodel.h"
#include <QTableView>
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
WeaponModel model;
QTableView view;
view.setModel(&model);
view.setWindowTitle(QString("表格视图"));
view.resize(600,400);
view.show();
return app.exec();
}
以上是关于表格视图D的主要内容,如果未能解决你的问题,请参考以下文章
如何使用列表视图在选项卡式活动的片段中呈现 SQLite 表数据 [重复]