Qt浅谈之十九:Model/View实现表格和统计图

2024-03-11 11:08

本文主要是介绍Qt浅谈之十九:Model/View实现表格和统计图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、简介

       Model/View结构使数据管理与相应的数据显示相互独立,并提供了一系列标准的函数接口和用于Model模块与View模块之间的通信。它从MVC演化而来,MVC由三种对象组成,Model是应用程序对象,View是它的屏幕表示,Controller定义了用户界面如何对用户输入进行响应。把MVC中的View和Controller合在一起,就形成了Model/View结构。

二、运行图

(1)为了灵活对用户的输入进行处理,引入了Delegate,Model、View、Delegate三个模块之间通过信号与槽机制实现,当自身的状态发生改变时会发出信号通知其他模块。它们间的关系如下图1所示。

       QAbstractItemModel是所有Model的基类,但一般不直接使用QAbstractItemModel,而是使用它的子类。Model模块本身并不存储数据,而是为View和Delegate访问数据提供标准的接口。

       View模块从Model中获得数据项显示给用户,Qt提供了一些常用的View模型,如QTreeView、QTableView和QListView。

       Delegate的基本接口在QAbstractItemDelegate类中定义,通过实现paint()和sizeHint()以达到渲染数据项的目的。

(2)程序运行图如下图2所示。


三、详解

1、表格中嵌入控件

利用Delegate的方式实现表格中嵌入各种不同控件的效果,控件在需要编辑数据项时才出现。

(1)插入日历编辑框QDateLineEdit

#ifndef DATEDELEGATE_H
#define DATEDELEGATE_H#include <QtGui>class DateDelegate : public QItemDelegate
{Q_OBJECTpublic:DateDelegate(QObject *parent = 0);QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const;void setEditorData(QWidget *editor, const QModelIndex &index) const;void setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const;void updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &index) const;
};#endif
#include "datedelegate.h"DateDelegate::DateDelegate(QObject *parent): QItemDelegate(parent)
{
}QWidget *DateDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &/* option */,const QModelIndex &/* index */) const
{QDateTimeEdit *editor = new QDateTimeEdit(parent);editor->setDisplayFormat("yyyy-MM-dd");editor->setCalendarPopup(true);editor->installEventFilter(const_cast<DateDelegate*>(this));return editor;
}void DateDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{QString dateStr = index.model()->data(index).toString();QDate date = QDate::fromString(dateStr,Qt::ISODate);QDateTimeEdit *edit = static_cast<QDateTimeEdit*>(editor);edit->setDate(date);
}void DateDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const
{QDateTimeEdit *edit = static_cast<QDateTimeEdit*>(editor);QDate date = edit->date();model->setData(index, QVariant(date.toString(Qt::ISODate)));
}void DateDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{editor->setGeometry(option.rect);
}
       分析:DateDelegate继承QItemDelegate,一般需要重定义声明中的几个虚函数。createEditor()函数完成创建控件的工作;setEditorDate()设置控件显示的数据,把Model数据更新至Delegate,相当于初始化工作;setModelDate()把Delegate中对数据的更改更新至Model中;updateEditor()更析控件区的显示。

(2)插入下拉列表框QComboBox

#include "combodelegate.h"ComboDelegate::ComboDelegate(QObject *parent): QItemDelegate(parent)
{
}QWidget *ComboDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &/* option */,const QModelIndex &/* index */) const
{QComboBox *editor = new QComboBox(parent);editor->addItem(QString::fromLocal8Bit("工人"));editor->addItem(QString::fromLocal8Bit("农民"));editor->addItem(QString::fromLocal8Bit("医生"));editor->addItem(QString::fromLocal8Bit("律师"));editor->addItem(QString::fromLocal8Bit("军人"));editor->installEventFilter(const_cast<ComboDelegate*>(this));return editor;
}void ComboDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{QString str = index.model()->data(index).toString();QComboBox *box = static_cast<QComboBox*>(editor);int i = box->findText(str);box->setCurrentIndex(i);
}void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const
{QComboBox *box = static_cast<QComboBox*>(editor);QString str = box->currentText();model->setData(index, str);
}void ComboDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{editor->setGeometry(option.rect);
}

(3)插入微调器QSpinBox

#include "spindelegate.h"SpinDelegate::SpinDelegate(QObject *parent): QItemDelegate(parent)
{
}QWidget *SpinDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem &/* option */,const QModelIndex &/* index */) const
{QSpinBox *editor = new QSpinBox(parent);editor->setRange(1000,10000);    editor->installEventFilter(const_cast<SpinDelegate*>(this));return editor;
}void SpinDelegate::setEditorData(QWidget *editor,const QModelIndex &index) const
{int value = index.model()->data(index).toInt();QSpinBox *spin = static_cast<QSpinBox*>(editor);spin->setValue(value);
}void SpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const
{QSpinBox *spin = static_cast<QSpinBox*>(editor);int value = spin->value();model->setData(index, value);
}void SpinDelegate::updateEditorGeometry(QWidget *editor,const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{editor->setGeometry(option.rect);
}

2、柱状统计图

自定义的View实现一个柱状统计图对TableModel的表格数据进行显示。
#ifndef HISTOGRAMVIEW_H
#define HISTOGRAMVIEW_H#include <QtGui>class HistogramView : public QAbstractItemView
{Q_OBJECT
public:HistogramView(QWidget *parent=0);QRect visualRect(const QModelIndex &index)const;void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible);QModelIndex indexAt(const QPoint &point) const;    void paintEvent(QPaintEvent *);void mousePressEvent(QMouseEvent *);void setSelectionModel(QItemSelectionModel * selectionModel);QRegion itemRegion(QModelIndex index);  protected slots:void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);void selectionChanged(const QItemSelection & selected, const QItemSelection & deselected );protected:QModelIndex moveCursor(QAbstractItemView::CursorAction cursorAction,Qt::KeyboardModifiers modifiers);int horizontalOffset() const;int verticalOffset() const;    bool isIndexHidden(const QModelIndex &index) const;void setSelection ( const QRect&rect, QItemSelectionModel::SelectionFlags flags );QRegion visualRegionForSelection(const QItemSelection &selection) const;       private:QItemSelectionModel *selections; QList<QRegion> listRegionM;  QList<QRegion> listRegionF; QList<QRegion> listRegionS; };#endif 
#include "histogramview.h"HistogramView::HistogramView(QWidget *parent): QAbstractItemView(parent)
{}void HistogramView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{QAbstractItemView::dataChanged(topLeft, bottomRight);viewport()->update();
}QRect HistogramView::visualRect(const QModelIndex &index) const
{}void HistogramView::scrollTo(const QModelIndex &index, ScrollHint hint)
{}QModelIndex HistogramView::indexAt(const QPoint &point) const
{QPoint newPoint(point.x(),point.y());QRegion region;foreach(region,listRegionM){if (region.contains(newPoint)){int row = listRegionM.indexOf(region);QModelIndex index = model()->index(row, 3,rootIndex());return index;}}return QModelIndex();
}QModelIndex HistogramView::moveCursor(QAbstractItemView::CursorAction cursorAction,Qt::KeyboardModifiers modifiers)
{}int HistogramView::horizontalOffset() const
{
}int HistogramView::verticalOffset() const
{}bool HistogramView::isIndexHidden(const QModelIndex &index) const
{}void HistogramView::setSelectionModel(QItemSelectionModel * selectionModel)
{selections = selectionModel;
}void HistogramView::mousePressEvent(QMouseEvent *e)
{QAbstractItemView::mousePressEvent(e);setSelection(QRect(e->pos().x(),e->pos().y(),1,1),QItemSelectionModel::SelectCurrent);    
}QRegion HistogramView::itemRegion(QModelIndex index)
{QRegion region;if (index.column() == 3)region = listRegionM[index.row()];return region;
}void HistogramView::setSelection ( const QRect &rect, QItemSelectionModel::SelectionFlags flags )
{int rows = model()->rowCount(rootIndex());int columns = model()->columnCount(rootIndex());QModelIndex selectedIndex;for (int row = 0; row < rows; ++row) {for (int column = 1; column < columns; ++column) {QModelIndex index = model()->index(row, column, rootIndex());QRegion region = itemRegion(index);if (!region.intersected(rect).isEmpty())selectedIndex = index;}}if(selectedIndex.isValid()) selections->select(selectedIndex,flags);else {QModelIndex noIndex;selections->select(noIndex, flags);}
}QRegion HistogramView::visualRegionForSelection(const QItemSelection &selection) const
{}void HistogramView::selectionChanged(const QItemSelection & selected, const QItemSelection & deselected )
{viewport()->update();
}void HistogramView::paintEvent(QPaintEvent *)
{QPainter painter(viewport());painter.setPen(Qt::black);int x0 = 40;int y0 = 250;// draw coordinate  painter.drawLine(x0, y0, 40, 30);painter.drawLine(38, 32, 40, 30);painter.drawLine(40, 30, 42, 32);painter.drawText(5, 45, tr("income"));for (int i=1; i<5; i++) {painter.drawLine(-1,-i*50,1,-i*50);painter.drawText(-20,-i*50,tr("%1").arg(i*5));}// x轴painter.drawLine(x0, y0, 540, 250);painter.drawLine(538, 248, 540, 250);painter.drawLine(540, 250, 538, 252);painter.drawText(500, 270, tr("name"));int row;// nameint posD = x0+20;for (row = 0; row < model()->rowCount(rootIndex()); row++) {QModelIndex index = model()->index(row, 0, rootIndex());QString dep = model()->data(index).toString();    painter.drawText(posD,y0+20,dep);posD += 50;}// incomeint posM = x0+20;for (row = 0; row < model()->rowCount(rootIndex()); row++){QModelIndex index = model()->index(row, 3, rootIndex());int income = model()->data(index).toDouble();int width = 10;if (selections->isSelected(index))painter.setBrush(QBrush(Qt::darkBlue,Qt::SolidPattern));elsepainter.setBrush(Qt::blue);painter.drawRect(QRectF(posM + 10, y0-income/25, width, income/25));QRegion regionM(posM + 10, y0-income/25, width, income/25);listRegionM << regionM;posM += 50;}
}
       分析:对父类的QAbstractItemView中的所有纯虚函数都必须进行声明, 纯虚函数包括visualRect()、scrollTo()、indexAt()、moveCursor()、horizontalOffset()、verticalOffset()、isIndexHidden()、setSelection()和visualRegionForSelection(),这些函数并不一定都要实现,根据功能要求选择实现。

四、总结

(1)Mode/View结构比较难于理解,在此先作简单的介绍,以后再进行更加深入的研究。

(2)感兴趣的可以下载源码分析,并在其基础上进行自己的开发,本人水平有限,也只能提供代码供读者延伸。

(3)源码已经打包上传到csdn上可登录下载(http://download.csdn.net/detail/taiyang1987912/7797583)。  

(4)若有更好的设计建议,也可发邮件沟通,在此先感谢!邮箱地址yang.ao@i-soft.com.cn。

这篇关于Qt浅谈之十九:Model/View实现表格和统计图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/797631

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库