offsetsTableModel offsetsModel;
QTableView *offsetsTableView=new QTableView();[code=C/C++]
offsetsTableView->setShowGrid(true);
offsetsTableView->setModel(&offsetsModel);
offsetsTableView->setAlternatingRowColors(true);
QLabel *aa= new QLabel(tr("qwert"));
QVBoxLayout *aaa= new QVBoxLayout;
aaa->addWidget(aa);
aaa->addWidget(offsetsTableView);
this->setLayout(aaa);[/code]
子类化QAbstractTableModel
.cpp
#ifndef OFFSETSTABLEMODEL_H
#define OFFSETSTABLEMODEL_H
#include <QAbstractTableModel>
class offsetsTableModel:public QAbstractTableModel
{
public:
offsetsTableModel();
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<QVector<double> > offsets;
};
#endif // OFFSETSTABLEMODEL_H
.h
#include "shipwindow.h"
#include <QtGui>
#include "mainwindow.h"
#include <QDebug>
#include <QVector>
#include <offsetstablemodel.h>
extern QVector<QVector<double> > xingzhi;//外部全局变量,在其他文件已读入数据
offsetsTableModel::offsetsTableModel()
{
// qDebug()<<xingzhi;
}
int offsetsTableModel::rowCount(const QModelIndex &parent) const
{
// qDebug()<<(xingzhi.size()-1); 有输出
return (xingzhi.size()-1);
}
int offsetsTableModel::columnCount(const QModelIndex &parent) const
{
// qDebug()<<(xingzhi.at(0).size()-1); 有输出
return (xingzhi.at(0).size()-1);
}
QVariant offsetsTableModel::data(const QModelIndex &index, int role) const
{
qDebug()<<"w"; // 没输出
if (!index.isValid())
return QVariant();
if (role == Qt::TextAlignmentRole) {
return int(Qt::AlignRight | Qt::AlignVCenter);
} else if (role == Qt::DisplayRole) {
// qDebug()<<"wang";
double tableViewOffsets= xingzhi.at(index.row()+1).at(index.column()+1);
qDebug()<<tableViewOffsets;
return tableViewOffsets;
// return QString("%1").arg(tableViewOffsets, 0, 'f', 4);
}
return QVariant();
}
//section和index.row()都是从0开始
QVariant offsetsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role!=Qt::DisplayRole)
return QVariant();
if(orientation==Qt::Horizontal)
{
return tr("%1m水线").arg(xingzhi.at(0).at(section+1));
// return xingzhi.at(0).at(section+1);
}
if(orientation==Qt::Vertical)
{
return tr("%1站").arg(xingzhi.at(section+1).at(0));
}
return QVariant();
}
程序能运行,也能出现tableview,但是数据不显示,表头不显示,也没有网格