Qt实现自定义模型基于QAbstractTableModel

两个例子

例子1代码

Main.cpp

#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);
currencyMap.insert("EUR", 0.8333);
currencyMap.insert("GBP", 0.5661);
currencyMap.insert("HKD", 7.7562);
currencyMap.insert("JPY", 112.92);
currencyMap.insert("NOK", 6.5200);
currencyMap.insert("NZD", 1.4697);
currencyMap.insert("SEK", 7.8180);
currencyMap.insert("SGD", 1.6901);
currencyMap.insert("USD", 1.0000); //自定义表模型
CurrencyModel currencyModel;
currencyModel.setCurrencyMap(currencyMap);
//表视图
QTableView tableView;
//设置视图模型
tableView.setModel(&currencyModel);
//设置交替颜色
tableView.setAlternatingRowColors(true); tableView.setWindowTitle(QObject::tr("Currencies"));
tableView.show(); return app.exec();
}

currencymodel.h

#ifndef CURRENCYMODEL_H
#define CURRENCYMODEL_H #include <QAbstractTableModel>
#include <QMap> class CurrencyModel : public QAbstractTableModel
{
public:
CurrencyModel(QObject *parent = ); 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

currencymodel.cpp

#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, , 'f', );
}
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();
}

例子2代码

Main.cpp

#include <QApplication>
#include <QHeaderView>
#include <QTableView> #include "citymodel.h" int main(int argc, char *argv[])
{
QApplication app(argc, argv); //保存城市名
QStringList cities;
cities << "Arvika" << "Boden" << "Eskilstuna" << "Falun"
<< "Filipstad" << "Halmstad" << "Helsingborg" << "Karlstad"
<< "Kiruna" << "Kramfors" << "Motala" << "Sandviken"
<< "Skara" << "Stockholm" << "Sundsvall" << "Trelleborg";
//模型
CityModel cityModel;
//
cityModel.setCities(cities); QTableView tableView;
tableView.setModel(&cityModel);
tableView.setAlternatingRowColors(true);
tableView.setWindowTitle(QObject::tr("Cities"));
tableView.show(); return app.exec();
}

citymodel.h

#ifndef CITYMODEL_H
#define CITYMODEL_H #include <QAbstractTableModel>
#include <QStringList>
#include <QVector> class CityModel : public QAbstractTableModel
{
Q_OBJECT public:
CityModel(QObject *parent = ); void setCities(const QStringList &cityNames);
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value,
int role);
QVariant headerData(int section, Qt::Orientation orientation,
int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const; private:
int offsetOf(int row, int column) const; QStringList cities;
QVector<int> distances;
}; #endif

citymodel.cpp

#include <QtCore>

#include "citymodel.h"

CityModel::CityModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
//设定一下数据源
void CityModel::setCities(const QStringList &cityNames)
{
cities = cityNames;
//重新设置一下QVector distances的矩阵大小的,中间对角线为0不用存
distances.resize(cities.count() * (cities.count() - ) / );
//填充所有距离值为0
distances.fill();
//刷新所有视图数据
reset();
}
//模型行数
int CityModel::rowCount(const QModelIndex & /* parent */) const
{
return cities.count();
}
//模型列数
int CityModel::columnCount(const QModelIndex & /* parent */) const
{
return cities.count();
}
//赋值模型每个项的数据
QVariant CityModel::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) {
if (index.row() == index.column())
return ;
int offset = offsetOf(index.row(), index.column());
return distances[offset];
}
return QVariant();
}
//编辑一个项
bool CityModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
if (index.isValid() && index.row() != index.column()
&& role == Qt::EditRole) {
int offset = offsetOf(index.row(), index.column());
distances[offset] = value.toInt();
//交换对应项的模型索引
QModelIndex transposedIndex = createIndex(index.column(),
index.row());
//某项发生改变,发射信号( between topLeft and bottomRight inclusive)
emit dataChanged(index, index);
emit dataChanged(transposedIndex, transposedIndex);
return true;
}
return false;
} //返回列表头
QVariant CityModel::headerData(int section,
Qt::Orientation /* orientation */,
int role) const
{
//返回在Cities字符串列表中给定偏移量的城市名称
if (role == Qt::DisplayRole)
return cities[section];
return QVariant();
}
//返回对一个项相关的操作的标识符(例如,是否可以编辑或者是否已选中等)
Qt::ItemFlags CityModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.row() != index.column())
flags |= Qt::ItemIsEditable;
return flags;
}
//计算偏移量
int CityModel::offsetOf(int row, int column) const
{
if (row < column)
qSwap(row, column);
return (row * (row - ) / ) + column;
}

转自:http://qimo601.iteye.com/blog/1534331

(四)Qt实现自定义模型基于QAbstractTableModel (一般)的更多相关文章

  1. (五)Qt实现自定义模型基于QAbstractItemModel

    一个小例子 QTableView + QStandardItemModel QStandardItemModel model; //设置大小 model.setColumnCount(); //列 m ...

  2. Qt5MV自定义模型与实例浅析

    1. Model/View结构 这种结构,其实就是将界面组件与所编辑的数据分离开来,又通过数据源的方式连接起来,相当于解耦,视图层只关心显示和与用户交互,而数据层负责与实际的数据进行通信,并为视图组件 ...

  3. Qt的事件模型(5种使用办法,通常重新实现event handler即可。只有定义控件才需要管理信号的发射)

    Qt的事件模型 1.事件的概念 应用程序对象将系统消息接收为 Qt 事件.应用程序可以按照不同的粒度对事件加以监控.过滤并做出响应. 在 Qt 中,事件是指从 QEvent继承 的对象.Qt将事件发送 ...

  4. Qt之自定义托盘(二)

    上一篇文章讲述了自定义Qt托盘,不过不是使用QSystemTrayIcon这个类,而是我们自己完全自定义的一个类,我们只需要处理这个类的鼠标hover.鼠标左键点击.鼠标右键点击和鼠标左键双击,就可以 ...

  5. 一个I/O线程可以并发处理N个客户端连接和读写操作 I/O复用模型 基于Buf操作NIO可以读取任意位置的数据 Channel中读取数据到Buffer中或将数据 Buffer 中写入到 Channel 事件驱动消息通知观察者模式

    Tomcat那些事儿 https://mp.weixin.qq.com/s?__biz=MzI3MTEwODc5Ng==&mid=2650860016&idx=2&sn=549 ...

  6. QT中自定义系统托盘的实现—c++语言为例

    将要介绍的是:QT中自定义系统托盘(systemtray)的一个Demo,希望能帮需要的读者快速上手. 前提假设是诸位已经知道QT中的signals .slot以及资源文件,所以关于这些不会再累述. ...

  7. 封装:简要介绍自定义开发基于WPF的MVC框架

    原文:封装:简要介绍自定义开发基于WPF的MVC框架 一.目的:在使用Asp.net Core时,深感MVC框架作为页面跳转数据处理的方便,但WPF中似乎没有现成的MVC框架,由此自定义开发一套MVC ...

  8. [Qt插件]-03创建Qt Designer自定义部件

    如何创建自定义部件并添加到Qt Designer来爽快的拖动部件可视化界面设计?   Qt Designer基于插件的架构使得它可以使用用户设计或者第三方提供的自定义部件,就像使用标准的Qt部件一样. ...

  9. PyQt(Python+Qt)学习随笔:基于项的项部件(Item Widgets(Item-Based))概述

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 Model/View架构中的视图部件是基于模型的项视图(Item Views(Model-Based ...

随机推荐

  1. wamp2.4-- 为WAMP中的mysql设置密码密码

    WAMP安装好后,mysql密码是为空的,那么要如何修改呢?其实很简单,通过几条指令就行了,下面我就一步步来操作. 1.首先,通过WAMP打开mysql控制台.提示输入密码,因为现在是空,所以直接按回 ...

  2. Workflow_标准控件Wait_For_Flow和Contiune_Flow的用法(案例)

    2014-06-04 Created By BaoXinjian

  3. Oracle监听配置、数据库实例配置等

    参考:http://jingyan.baidu.com/article/3aed632e7a638b70108091dd.html linux下面搞Orale参考:http://blog.sina.c ...

  4. kafka工作原理简介

    消息队列 消息队列技术是分布式应用间交换信息的一种技术.消息队列可驻留在内存或磁盘上, 队列存储消息直到它们被应用程序读走.通过消息队列,应用程序可独立地执行--它们不需要知道彼此的位置.或在继续执行 ...

  5. wxWidgets编程起步

    開始学习wxWidgets,上一篇写了"安装wxWidgets遭遇的两大关卡"(简称"前文"). 先推荐一下这两天找到的学习材料. 博客中有一个系列教程,貌似作 ...

  6. MYSQL加入远程用户或同意远程訪问三种方法

    加入远程用户admin密码为password GRANT ALL PRIVILEGES ON *.* TO admin@localhost IDENTIFIED BY \'password\' WIT ...

  7. 批处理学习笔记9 - 深入学习For命令2

    这一篇是对于for /f的扩展,上一篇说道/f可以读txt文件里的数据.这里了解下tokens和delims功能 平常文本文件保存数据经常用这样的格式 avi|wmv|rm|mkv|mp4 以读取这个 ...

  8. MD5加密 时间差 流水号等方法

    /// <summary> /// 使用TimeSpan计算两个时间差 /// </summary> /// <param name="DateTime1&qu ...

  9. [转帖]cocos2D-X源码分析之从cocos2D-X学习OpenGL(3)----BATCH_COMMAND

    原贴: cocos2D-X源码分析之从cocos2D-X学习OpenGL(3)----BATCH_COMMAND 上一篇介绍了QUAD_COMMAND渲染命令,顺带介绍了VAO和VBO,这一篇介绍批处 ...

  10. qt 例子地址

    http://blog.sina.com.cn/s/articlelist_2801495241_0_2.html qt打包http://blog.chinaunix.net/uid-24641004 ...