(四)Qt实现自定义模型基于QAbstractTableModel (一般)
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(¤cyModel);
//设置交替颜色
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 (一般)的更多相关文章
- (五)Qt实现自定义模型基于QAbstractItemModel
一个小例子 QTableView + QStandardItemModel QStandardItemModel model; //设置大小 model.setColumnCount(); //列 m ...
- Qt5MV自定义模型与实例浅析
1. Model/View结构 这种结构,其实就是将界面组件与所编辑的数据分离开来,又通过数据源的方式连接起来,相当于解耦,视图层只关心显示和与用户交互,而数据层负责与实际的数据进行通信,并为视图组件 ...
- Qt的事件模型(5种使用办法,通常重新实现event handler即可。只有定义控件才需要管理信号的发射)
Qt的事件模型 1.事件的概念 应用程序对象将系统消息接收为 Qt 事件.应用程序可以按照不同的粒度对事件加以监控.过滤并做出响应. 在 Qt 中,事件是指从 QEvent继承 的对象.Qt将事件发送 ...
- Qt之自定义托盘(二)
上一篇文章讲述了自定义Qt托盘,不过不是使用QSystemTrayIcon这个类,而是我们自己完全自定义的一个类,我们只需要处理这个类的鼠标hover.鼠标左键点击.鼠标右键点击和鼠标左键双击,就可以 ...
- 一个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 ...
- QT中自定义系统托盘的实现—c++语言为例
将要介绍的是:QT中自定义系统托盘(systemtray)的一个Demo,希望能帮需要的读者快速上手. 前提假设是诸位已经知道QT中的signals .slot以及资源文件,所以关于这些不会再累述. ...
- 封装:简要介绍自定义开发基于WPF的MVC框架
原文:封装:简要介绍自定义开发基于WPF的MVC框架 一.目的:在使用Asp.net Core时,深感MVC框架作为页面跳转数据处理的方便,但WPF中似乎没有现成的MVC框架,由此自定义开发一套MVC ...
- [Qt插件]-03创建Qt Designer自定义部件
如何创建自定义部件并添加到Qt Designer来爽快的拖动部件可视化界面设计? Qt Designer基于插件的架构使得它可以使用用户设计或者第三方提供的自定义部件,就像使用标准的Qt部件一样. ...
- PyQt(Python+Qt)学习随笔:基于项的项部件(Item Widgets(Item-Based))概述
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 Model/View架构中的视图部件是基于模型的项视图(Item Views(Model-Based ...
随机推荐
- shell 基本学习
1)查看当前shell echo $SHELL 2)查看兼容shell more /etc/shells 3) 脚本第一行 #!/bin/bash 4) 变量(变量名称的开头是一个字母或下划线符号,后 ...
- django的hello world 项目
一.新建一个django项目bester: django-admin startproject bester 二.在bester项目中建一个叫polls的应用程序: cd bester/ python ...
- Spring中的内部Bean
简介 当一个bean仅被用作另一个bean的属性时,它能被声明为一个内部bean,为了定义inner bean,在Spring 的 基于XML的 配置元数据中,可以在 <property/> ...
- (转) 共享个很棒的vim配置
发现了一个很棒的vim配置方法,现在共享给大家. https://github.com/kepbod/ivim ivim - The Vim Distribution of Xiao-Ou Zha ...
- mysqldump 报导常
Warning: A partial dump from a server that has GTIDs will by default include the GTIDs of all transa ...
- hdoj 1166 敌兵布阵 线段数和树状数组
敌兵布阵 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submis ...
- How to Reuse Old PCs for Solr Search Platform?
家裡或公司的舊電腦不夠力? 效能慢到想砸爛它們? 朋友或同事有電腦要丟嗎? 我有一個廢物利用的方法, 我收集了四台舊電腦, 組了一個Fully Distributed Mode的Hadoop Clus ...
- 你应该知道的Virtual Studio
最近,在网上看到一篇关于VS2008的一些提示,可以提高开发效率,我把它翻译过来,当然里面也有很多自己的想法,分享一下,大家可以择有用的提示而用之. 参考:每个开发者都应该知道的提示和诀窍 提示一:拷 ...
- ARM GNU常用汇编语言介绍
ARM GNU常用汇编语言介绍 ARM汇编语言源程序语句,一般由指令,伪操作,宏指令和伪指令组成. ARM汇编语言的设计基础是汇编伪指令,汇编伪操作和宏指令. 伪操作,是ARM汇编语言程序里的一些特殊 ...
- encoding/path可能引起无数奇怪的问题
例如如下代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageE ...