自定义只读模型
,cpp文件源码
#include "currencymodel.h"
CurrencyModel::CurrencyModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
CurrencyModel::~CurrencyModel()
{
}
int CurrencyModel::rowCount(const QModelIndex &parent) const
{
return currencyMap.count();
}
int CurrencyModel::columnCount(const QModelIndex & parent)const
{
return currencyMap.count();
}
QVariant CurrencyModel::headerData( int section,Qt::Orientation,int role) const
{
if (role !=Qt::DisplayRole)
{
return QVariant();
}
return currencyAt(section);
}
QString CurrencyModel::currencyAt(int offset) const
{
return(currencyMap.begin()+offset).key();
}
void CurrencyModel::setCurrencyMap(const QMap<QString,double> &map)
{
beginResetModel(); // 写一种协议
currencyMap = map;
endResetModel();
}
QVariant CurrencyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (role == Qt::TextAlignmentRole) {
return int(Qt::AlignRight | Qt::AlignVCenter);
}
else if (role == Qt::DisplayRole) {
QString rowCurrency = currencyAt(index.row());
QString columnCurrency = currencyAt(index.column());
if (currencyMap.value(rowCurrency) == 0.0) {
return "####";
}
double amount = currencyMap.value(columnCurrency)
/ currencyMap.value(rowCurrency);
return QString("%1").arg(amount, 0, 'f', 4);
}
return QVariant();
}
.h 文件源码
#ifndef CURRENCYMODEL_H
#define CURRENCYMODEL_H
#include <QAbstractTableModel>
class CurrencyModel : public QAbstractTableModel
{
Q_OBJECT
public:
CurrencyModel(QObject *parent=0);
~CurrencyModel();
void setCurrencyMap(const QMap<QString, double> &map); // 非const的成员函数不可以被const的对象访问
int rowCount(const QModelIndex &parent) const; // this指针常量化 任何修改this成员变量的操作都是不允许的 即可被const对象访问也可以被非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:
QString currencyAt(int offset) const;
QMap<QString, double> currencyMap;
};
#endif // CURRENCYMODEL_H
mian 函数的实现代码 :
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMap<QString, double> data;
data["USD"] = 1.0000;
data["CNY"] = 0.1628;
data["GBP"] = 1.5361;
data["EUR"] = 1.2992;
data["HKD"] = 0.1289;
QTableView view;
CurrencyModel *model = new CurrencyModel(&view);
model->setCurrencyMap(data);
view.setModel(model);
view.resize(400, 300);
view.show();
return app.exec();
}
实现效果:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
intmain(intargc,char*argv[])
{
QApplicationa(argc,argv);
QMap<QString,double>data;
data["USD"]=1.0000;
data["CNY"]=0.1628;
data["GBP"]=1.5361;
data["EUR"]=1.2992;
data["HKD"]=0.1289;
QTableViewview;
CurrencyModel
*model=newCurrencyModel(&view);
model->setCurrencyMap(data);
view.setModel(model);
view.resize(400,300);
view.show();
returna.exec();
}
|