-
UID:124427
-
- 注册时间2011-11-14
- 最后登录2023-01-12
- 在线时间11小时
-
- 发帖3
- 搜Ta的帖子
- 精华0
- 金钱30
- 威望13
- 贡献值0
- 好评度3
-
访问TA的空间加好友用道具
|
采用 C++ GUI Qt 4书中的源码例子,数据 显示正确,列 标题显示1,2,3,4,源码如下 - #ifndef CURRENCYMODEL_H
- #define CURRENCYMODEL_H
-
- #include <QAbstractTableModel>
- #include <QMap>
-
- class CurrencyModel : public QAbstractTableModel
- {
- public:
- CurrencyModel(QObject *parent = 0);
-
- void setCurrencyMap(const QMap<QString, double> &map);
- 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:
- QString currencyAt(int offset) const;
-
- QMap<QString, double> currencyMap;
- };
-
- #endif
- #include <QtCore>
-
- #include "currencymodel.h"
-
- CurrencyModel::CurrencyModel(QObject *parent)
- : QAbstractTableModel(parent)
- {
- }
-
- void CurrencyModel::setCurrencyMap(const QMap<QString, double> &map)
- {
- currencyMap = map;
- //重置模型至原始状态,告诉所有视图,他们数据都无效,强制刷新数据
- reset();
- }
-
- //返回行数
- int CurrencyModel::rowCount(const QModelIndex & /* parent */) const
- {
- return currencyMap.count();
- }
- //返回列数
- int CurrencyModel::columnCount(const QModelIndex & /* parent */) const
- {
- return currencyMap.count();
- }
-
- //返回一个项的任意角色的值,这个项被指定为QModelIndex
- 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();
- }
- //返回表头名称,(行号或列号,水平或垂直,角色)
- QVariant CurrencyModel::headerData(int section,
- Qt::Orientation /* orientation */,
- int role) const
- {
- if (role != Qt::DisplayRole)
- return QVariant();
- return currencyAt(section);
- }
- //获取当前关键字
- QString CurrencyModel::currencyAt(int offset) const
- {
- return (currencyMap.begin() + offset).key();
- }
- #include <QtGui>
-
- #include "currencymodel.h"
-
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
-
- //数据源
- QMap<QString, double> currencyMap;
- currencyMap.insert("AUD", 1.3259);
- currencyMap.insert("CHF", 1.2970);
- currencyMap.insert("CZK", 24.510);
- currencyMap.insert("DKK", 6.2168);
-
- //自定义表模型
- CurrencyModel *currencyModel=new CurrencyModel ;
- currencyModel->setCurrencyMap(currencyMap);
- //表视图
- QTableView tableView;
- //设置视图模型
- tableView.setModel(currencyModel);
- tableView.show();
-
- return app.exec();
- }
|