(四)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(&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 = 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

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

例子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_OBJECTpublic:CityModel(QObject *parent = 0);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() - 1) / 2);//填充所有距离值为0distances.fill(0);//刷新所有视图数据
    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 0;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 - 1) / 2) + column;
}

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

转载于:https://www.cnblogs.com/liushui-sky/p/5775579.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/374125.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

pt-query-digest使用介绍【转】

本文来自&#xff1a;http://isadba.com/?p651 一、pt-query-digest参数介绍. pt-query-digest --useranemometer --passwordanemometerpass --review h192.168.11.28,Dslow_query_log,tglobal_query_review \--history h192.168.11.28,Dslow_query_log,tglobal_query_re…

python代码模板_python 代码模板

python中的Module是比较重要的概念。常见的情况是&#xff0c;事先写好一个.py文 件&#xff0c;在另一个文件中需要import时&#xff0c;将事先写好的.py文件拷贝 到当前目录&#xff0c;或者是在sys.path中增加事先写好的.py文件所在的目录&#xff0c;然后import。这样的做法…

Java并发教程–重入锁

Java的synced关键字是一个很棒的工具–它使我们能够以一种简单可靠的方式来同步对关键部分的访问&#xff0c;而且也不难理解。 但是有时我们需要对同步进行更多控制。 我们要么需要分别控制访问类型&#xff08;读取和写入&#xff09;&#xff0c;要么使用起来很麻烦&#xf…

找出互联网类似以下图的实例

转载于:https://www.cnblogs.com/sghcjy/p/4978851.html

python比较运算符重载_python运算符重载

1、打印操作会首先尝试__str__和str内置函数&#xff0c;他通常返回一个用户友好显示。__repr__用于所有其他环境&#xff0c;用于交互式模式下提示回应以及repr函数&#xff0c;如果没有使用__str__&#xff0c;则会使用print和str。它通常返回一个编码字符串&#xff0c;可以…

使用Spring MVC开发Restful Web服务

REST简介 摘自Wikipedia&#xff1a; REST风格的体系结构由客户端和服务器组成。 客户端向服务器发起请求&#xff1b; 服务器处理请求并返回适当的响应。 请求和响应围绕资源表示的传递而构建。 资源本质上可以是可以解决的任何连贯且有意义的概念。 正如您所阅读的&#xff0…

深入Java核心 Java内存分配原理精讲

深入Java核心 Java内存分配原理精讲 Java内存分配与管理是Java的核心技术之一&#xff0c;之前我们曾介绍过Java的内存管理与内存泄露以及Java垃圾回收方面的知识&#xff0c;今天我们再次深入Java核心&#xff0c;详细介绍一下Java在内存分配方面的知识。一般Java在内存分配时…

iOS正则表达式(亲测,持续更新)

先来说说判断方法,书写不简介但是好理解: -(BOOL)isRealNmaeString:(NSString *)str{NSString *pattern "填写正则表达式";NSPredicate *pred [NSPredicate predicateWithFormat:"SELF MATCHES %", pattern];BOOL isMatch [pred evaluateWithObject:str…

python新建一个文件夹需要重新安装模块吗_解决pycharm每次新建项目都要重新安装一些第三方库的问题...

目前有三个解决办法&#xff0c;也是亲测有用的&#xff1a;第一个方法&#xff1a;因为之前有通过pycharm的project interpreter里的号添加过一些库&#xff0c;但添加的库只是指定的项目用的&#xff0c;如果想要用&#xff0c;就必须用之前的项目的python解释器&#xff0c;…

端到端测试的滥用–测试技术2

我的上一个博客是有关测试代码方法的一系列博客中的第一篇&#xff0c;概述了使用一种非常常见的模式从数据库检索地址的简单方案&#xff1a; …并描述了一种非常通用的测试技术&#xff1a; 不编写测试 &#xff0c; 而是手动进行所有操作。 今天的博客涵盖了另一种实践&…

[AlwaysOn Availability Groups]排查:AG超过RPO

[AlwaysOn Availability Groups]排查&#xff1a;AG超过RPO 排查&#xff1a;AG超过RPO 在异步提交的secondary上执行了切换&#xff0c;你可能会发现数据的丢失大于RPO&#xff0c;或者在计算可以忍受的数据都是超过了RPO。 1.通常原因 1.网络延迟太高&#xff0c;网络吞吐量太…

那些年困扰我们的Linux 的蠕虫、病毒和木马

虽然针对Linux的恶意软件并不像针对Windows乃至OS X那样普遍&#xff0c;但是近些年来&#xff0c;Linux面临的安全威胁却变得越来越多、越来越严重。个中原因包括&#xff0c;手机爆炸性的普及意味着基于Linux的安卓成为恶意黑 客最具吸引力的目标之一&#xff0c;以及使用Lin…

python单元测试框架unittest介绍和使用_Python+Selenium框架设计篇之-简单介绍unittest单元测试框架...

前面文章已经简单介绍了一些关于自动化测试框架的介绍&#xff0c;知道了什么是自动化测试框架&#xff0c;主要有哪些特点&#xff0c;基本组成部分等。在继续介绍框架设计之前&#xff0c;我们先来学习一个工具&#xff0c;叫unittest。unittest是一个单元测试框架&#xff0…

使用PowerMock模拟静态方法

在最近的博客中&#xff0c;我试图强调使用依赖注入的好处&#xff0c;并表达一种想法&#xff0c;即这种技术的主要好处之一是&#xff0c;通过在类之间提供高度的隔离&#xff0c;它可以使您更轻松地测试代码&#xff0c;并且得出的结论是&#xff0c;许多好的测试等于好的代…

多态之向上转型

//向上转型&#xff0c;子类引用指向父类对象 public class UpcastingDemo{ public static void main(String[] args){ Employee enew Employee(); System.out.println(e.grade); e.job(); e.run(); System.out.println("\n"); Manager mnew Manager(…

(转)FPGA异步时序和多时钟模块

http://bbs.ednchina.com/BLOG_ARTICLE_3019907.HTM 第六章 时钟域 有一个有趣的现象&#xff0c;众多数字设计特别是与FPGA设计相关的教科书都特别强调整个设计最好采用唯一的时钟域。换句话说&#xff0c;只有一个独立的网络可以驱动一个设计中所有触发器的时钟端口。虽然…

穆里尼奥:与范加尔风格不同,转变需要时间

据英媒报道&#xff0c;曼联主帅穆里尼奥近日向媒体表示自己很难继续遵循前任主帅范加尔的理念去建立球队&#xff0c;因为他们两人有着完全不同的想法。 穆里尼奥近日在接受BT Sport的采访时表示&#xff1a;“这份工作对于我来说最难的地方便是我与范加尔是非常不同的教练&am…

怎么检测不到我的音频_Linux 上的最佳音频编辑工具推荐 | Linux 中国

在 Linux 上&#xff0c;有很多种音频编辑器可供你选用。不论你是一个专业的音乐制作人&#xff0c;还是只想学学怎么做出超棒的音乐的爱好者&#xff0c;这些强大的音频编辑器都是很有用的工具。-- Ankush Das(作者)在 Linux 上&#xff0c;有很多种音频编辑器可供你选用。不论…

具有GlassFish和一致性的高性能JPA –第3部分

在我的四部分系列的第三部分中&#xff0c;我将解释将Coherence与EclipseLink和GlassFish结合使用的第二种策略。 这就是通过EclipseLink使用Coherence作为二级缓存&#xff08;L2&#xff09;的全部内容。 一般的做法 这种方法将Coherence数据网格应用于依赖于无法完全预加载到…

接口使用时注意

interface Service{ void doSome(); //方法的默认修饰符为public abstract } public class InterfaceNote implements Service{ //方法默认的修饰符为 default void doSome(){ System.out.println("做一些服务&#xff01;"); } public static void main(String…