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. JMeter学习笔记--JMeter监听器

    监听器(Listeners)是一种展示采样结果的测试元件,采样结果可以通过树.表格.图片加以展示,或者简单地写入某个结果文件之中. 注:不同的监听器通过不同的方式展示服务器响应信息,但它们都将同样的原 ...

  2. nginx实战四

    nginx负载均衡 Nginx通过upstream和proxy_pass实现了负载均衡.本质上也是Nginx的反向代理功能,只不过后端的server为多个. 1.简单的轮询 upstream www ...

  3. DevExpress下拉多选框 CheckComboboxEdit、CheckedListBoxControl

    CheckComboboxEdit //清空项            checkedComboBoxEdit1.Properties.Items.Clear(); //自定义数组            ...

  4. Eclipse color theme jsp javascript显示问题

    Q: 在eclipse 中,设置为sublime格式时, 在编辑器中,jsp中嵌套的javascript底色非常难看. A:在如下位置进行设置,Window -> Preferences-> ...

  5. Angularjs Module类的介绍及模块化依赖

    后面的学习我们会遵循一个控制器管理一个视图,一个路由对应一个视图的单一原则,所以再不会将controller控制器代码直接写到 index.html 中. 我们会应用到angular.js中强大的模块 ...

  6. Java:多线程,线程同步,synchronized关键字的用法(同步代码块、非静态同步方法、静态同步方法)

    关于线程的同步,可以使用synchronized关键字,或者是使用JDK 5中提供的java.util.concurrent.lock包中的Lock对象.本文探讨synchronized关键字. sy ...

  7. Java:几个正则式应用(检查汉字、日期、EMAIL、手机号码的合法性,替换字符串等)

    1. 检查输入是否为合法汉字 /** * 判断输入字符是否为有效汉字 * @param str 字符 * @return 是否合法汉字 */ public static boolean isValid ...

  8. jquery 可拖拽的窗体控件实现代码

    引入JQUERY框架.把这个控件代码放到一个js文件里面直接引入就可以了控件代码 $.fn.myDrag = function() { var self = $(this); self.css(&qu ...

  9. [na]那些OVER的封装(pppoe/ppp/ipsec)

    什么over什么,如pppoe, ppp的封装都在over对象之后,入下图: PPPOE Ipsec

  10. 使用VMware安装CentOS7步骤详情

    准备资料: CentOS-7-x86_64-Everything-1611 点击下载CentOS 对,资料就这些 第一步.  点击文件  再点击新建虚拟机 第二步 .点击完新建虚拟机之后会跳出一个窗口 ...