Qt扫盲-QTableView理论总结

QTableView理论总结

  • 一、概述
  • 二、导航
  • 三、视觉外观
  • 四、坐标系统
  • 五、示例代码
    • 1. 性别代理
    • 2. 学生信息模型
    • 3. 对应视图

一、概述

QTableView实现了一个tableview 来显示model 中的元素。这个类用于提供之前由QTable类提供的标准表,但这个是使用Qt的model/view架构提供的更灵活的方法。

QTableView类是Model/View类之一,是Qt的Model/View框架的一部分。

QTableView实现了由QAbstractItemView类定义的接口,以允许它显示由QAbstractItemModel类派生的 model 提供的数据。
在这里插入图片描述
总的来说,model/view 的方式来查看修改数据更加的方便和容易的。

二、导航

我们可以通过鼠标点击一个单元格,或者使用箭头键来导航表格中的单元格。因为 QTableView 默认启用tabKeyNavigation,我们还可以按Tab键和Backtab键在单元格之间移动。

三、视觉外观

表格的垂直头部可以通过函数verticalHeader()获得,水平头部可以通过函数horizontalHeader()获得。可以使用rowHeight()来获得表中每一行的高度。类似地,列的宽度可以使用columnWidth()得到。由于这两个部件都是普通部件,因此可以使用它们的hide()函数隐藏它们。

可以使用hideRow()、hideColumn()、showRow()和showColumn()来隐藏和显示行和列。可以使用selectRow()和selectColumn()来选择列。表格会根据 showGrid 属性显示一个网格。就想我把这个设置为 false 之后。就没有网格线啦。
在这里插入图片描述

表视图中显示的项与其他项视图中的项一样,都使用标准委托进行渲染和编辑。

我们还可以用 代理的方式:用下列列表来选择性别的方式
在这里插入图片描述

然而,对于某些任务来说,能够在表中插入其他控件有时是有用的。

用setIndexWidget()函数为特定的索引设置窗口组件,然后用indexWidget()检索窗口组件。

默认情况下,表中的单元格不会扩展以填充可用空间。
您可以通过拉伸最后的标题部分来让单元格填充可用空间。使用 horizontalHeader() 或 verticalHeader() 访问相关的 headerview 标题对象,并设置标题的stretchLastSection属性。

要根据每一列或每一行的空间需求来分配可用空间,可以调用视图的resizeColumnsToContents()或resizeRowsToContents()函数。来实现出下面这种效果。

在这里插入图片描述

四、坐标系统

对于某些特殊形式的表,能够在行和列索引以及控件坐标之间进行转换是很有用的。

rowAt()函数提供了指定行的视图的y坐标;行索引可以通过rowViewportPosition()获得对应的y坐标。

columnAt()和columnViewportPosition()函数提供了x坐标和列索引之间等价的转换操作。

五、示例代码

1. 性别代理

// SexComboxDelegate.h
#ifndef SEXCOMBOXDELEGATE_H
#define SEXCOMBOXDELEGATE_H#include <QObject>
#include <QStyledItemDelegate>
#include <QComboBox>class SexComboxDelegate : public QStyledItemDelegate
{Q_OBJECT
public:SexComboxDelegate(QObject *parent = nullptr);QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const override;void setEditorData(QWidget *editor, const QModelIndex &index) const override;void setModelData(QWidget *editor, QAbstractItemModel *model,const QModelIndex &index) const override;void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,const QModelIndex &index) const override;
};#endif // SEXCOMBOXDELEGATE_H// SexComboxDelegate.cpp
#include "SexComboxDelegate.h"SexComboxDelegate::SexComboxDelegate(QObject *parent)
{}QWidget *SexComboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{QComboBox *editor = new QComboBox(parent);editor->addItems(QStringList{"男", "女"});editor->setFrame(false);return editor;
}void SexComboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{QComboBox *combox = static_cast<QComboBox*>(editor);combox->setCurrentIndex(combox->findText(index.model()->data(index, Qt::DisplayRole).toString()));
}void SexComboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{QComboBox *combox = static_cast<QComboBox*>(editor);model->setData(index, combox->currentText(), Qt::EditRole);
}void SexComboxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{editor->setGeometry(option.rect);
}

2. 学生信息模型

// StudentModel.h
#ifndef STUDENTMODEL_H
#define STUDENTMODEL_H#include <QAbstractTableModel>
#include <QDebug>
#include <QColor>
#include <QBrush>
#include <QFont>class StudentModel: public QAbstractTableModel
{Q_OBJECT
public:StudentModel(QObject *parent = nullptr);int rowCount(const QModelIndex &parent = QModelIndex()) const override;int columnCount(const QModelIndex &parent = QModelIndex()) const override;QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;QVariant headerData(int section, Qt::Orientation orientation, int role) const override;bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;Qt::ItemFlags flags(const QModelIndex &index) const override;void setRow(int newRow);void setColumn(int newColumn);void setTableHeader(QList<QString> *header);void setTableData(QList<QList<QString>> *data);signals:void editCompleted(const QString &);public slots:void SlotUpdateTable();
private:int row = 0;int column = 0;QList<QString> *m_header;QList<QList<QString>> *m_data;
};#endif // STUDENTMODEL_H// StudentModel.cpp
#include "StudentModel.h"StudentModel::StudentModel(QObject *parent) : QAbstractTableModel(parent)
{}int StudentModel::rowCount(const QModelIndex &parent) const
{return row;
}int StudentModel::columnCount(const QModelIndex &parent) const
{return column;
}QVariant StudentModel::data(const QModelIndex &index, int role) const
{if(role == Qt::DisplayRole || role == Qt::EditRole){return (*m_data)[index.row()][index.column()];}if(role == Qt::TextAlignmentRole){return Qt::AlignCenter;}if(role == Qt::BackgroundRole &&  index.row() % 2 == 0){return QBrush(QColor(50, 50, 50));}return QVariant();
}QVariant StudentModel::headerData(int section, Qt::Orientation orientation, int role) const
{if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {if(m_header->count() - 1 >= section)return m_header->at(section);}//qDebug()<<role << "--" << Qt::BackgroundRole;//    if(role == Qt::BackgroundRole)
//    {
//        return QBrush(QColor(156, 233, 248));
//    }
//    if(role == Qt::ForegroundRole)
//    {
//         return QBrush(QColor(156, 233, 248));
//    }if(role == Qt::FontRole){return QFont(tr("微软雅黑"),10, QFont::DemiBold);}return QVariant();
}bool StudentModel::setData(const QModelIndex &index, const QVariant &value, int role)
{if (role == Qt::EditRole) {if (!checkIndex(index))return false;//save value from editor to member m_gridData(*m_data)[index.row()][index.column()] = value.toString();return true;}return false;
}Qt::ItemFlags StudentModel::flags(const QModelIndex &index) const
{return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}void StudentModel::setRow(int newRow)
{row = newRow;
}void StudentModel::setColumn(int newColumn)
{column = newColumn;
}void StudentModel::setTableHeader(QList<QString> *header)
{m_header = header;
}void StudentModel::setTableData(QList<QList<QString> > *data)
{m_data = data;
}void StudentModel::SlotUpdateTable()
{emit dataChanged(createIndex(0, 0), createIndex(row, column), {Qt::DisplayRole});
}

3. 对应视图

// StudentWD.h
#ifndef STUDENTWD_H
#define STUDENTWD_H#include <QWidget>
#include <Model/StudentModel.h>
#include <QFileDialog>
#include <QStandardPaths>
#include <QFile>
#include <QTextStream>
#include <Delegate/SpinBoxDelegate.h>
#include <Delegate/SexComboxDelegate.h>namespace Ui {
class StudentWD;
}class StudentWD : public QWidget
{Q_OBJECTpublic:explicit StudentWD(QWidget *parent = nullptr);~StudentWD();private slots:void on_ImportBtn_clicked();private:Ui::StudentWD *ui;StudentModel *model;SpinBoxDelegate *spinBoxDelegate;SexComboxDelegate *sexBoxDeleage;QList<QList<QString>> subject_table;QList<QString> subject_title;
};#endif // STUDENTWD_H
// StudentWD.cpp
#include "StudentWD.h"
#include "ui_StudentWD.h"StudentWD::StudentWD(QWidget *parent) :QWidget(parent),ui(new Ui::StudentWD),model(new StudentModel),spinBoxDelegate(new SpinBoxDelegate),sexBoxDeleage(new SexComboxDelegate)
{ui->setupUi(this);ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);}StudentWD::~StudentWD()
{delete ui;
}void StudentWD::on_ImportBtn_clicked()
{QString fileName = QFileDialog::getOpenFileName(this,tr("打开 csv 文件"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), tr("Txt Files (*.txt *.csv *.*)"));subject_table.clear();subject_title.clear();if(!fileName.isNull() && !fileName.isEmpty()){QFile file(fileName);if (!file.open(QIODevice::ReadOnly | QIODevice::Text))return;int i = 0;QTextStream in(&file);in.setCodec("UTF-8");while (!file.atEnd()) {QString line = file.readLine();if(i == 0){subject_title = line.split(",", QString::SkipEmptyParts);subject_title.last() = subject_title.last().trimmed();i++;continue;}subject_table.append(line.split(",", QString::SkipEmptyParts));subject_table.last().last() = subject_table.last().last().trimmed();}ui->Total_Subject_SB->setValue(subject_title.count());ui->Total_People_SB->setValue(subject_table.count());model->setColumn(subject_title.count());model->setRow(subject_table.count());model->setTableData(& subject_table);model->setTableHeader(& subject_title);ui->tableView->setModel(model);ui->tableView->setItemDelegateForColumn(0, spinBoxDelegate);ui->tableView->setShowGrid(true);ui->tableView->setItemDelegateForColumn(1, sexBoxDeleage);for (int i = 2; i < subject_table.count(); ++i) {ui->tableView->setItemDelegateForColumn(i, spinBoxDelegate);}ui->tableView->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);}}

对应的ui文件
在这里插入图片描述

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

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

相关文章

【Rust】Rust学习 第十四章进一步认识 Cargo 和 Crates.io

本章会讨论 Cargo 其他一些更为高级的功能&#xff0c;我们将展示如何&#xff1a; 使用发布配置来自定义构建将库发布到 crates.io使用工作空间来组织更大的项目从 crates.io 安装二进制文件使用自定义的命令来扩展 Cargo Cargo 的功能不止本章所介绍的&#xff0c;关于其全…

python 使用 pdf2image 库将PDF转换为图片

在 Ubuntu 上实现网络穿透&#xff1a;手把手教你搭建FRPS服务器 初环境步骤一&#xff1a;安装pdf2image库步骤二&#xff1a;导入必要的库步骤三&#xff1a;指定PDF文件路径步骤四&#xff1a;将PDF转换为图片步骤五&#xff1a;保存图像为图片文件完整代码运行结果 在数字化…

算法通关村第八关——轻松搞定翻转二叉树

二叉树有很多经典算法题&#xff0c;今天我们就来看一下二叉树里的翻转问题。 力扣226,给了一棵二叉树&#xff0c;要将二叉树整体翻转。 分析&#xff1a;观察图中翻转前后的二叉树&#xff0c;我们不难发现&#xff0c;翻转过程中&#xff0c;只需要把每一个节点的左右子节点…

如何在前端实现WebSocket发送和接收UDP消息(多线程模式)

目录 简介&#xff1a;步骤1&#xff1a;创建WebSocket连接步骤2&#xff1a;创建Web Workers步骤3&#xff1a;发送和接收UDP消息&#xff08;多线程模式&#xff09;结束语&#xff1a; 简介&#xff1a; 本文将继续介绍如何在前端应用中利用WebSocket技术发送和接收UDP消息…

jQuery使用(超详细)

一、jQuery介绍 1.JQuery简介 jQuery 是一个高效、精简并且功能丰富的 JavaScript 工具库。它提供的 API 易于使用且兼容众多浏览器&#xff0c;这让诸如 HTML 文档遍历和操作、事件处理、动画和 Ajax 操作更加简单。目前超过90%的网站都使用了jQuery库&#xff0c;jQuery的宗…

为什么贴片电阻的阻值不规律?为了在某精度下做到阻值的全覆盖(对,但不全对),E系列电阻的算法(E12系列值不对的猜想)

1、先放上E系列的电阻表格 E12精度10%&#xff0c;E24精度5%&#xff0c;E96精度1%&#xff1b; 2、以精度作为条件的演算 通常我们选择电阻&#xff0c;要确定电阻的精度&#xff0c;如果以精度作为条件。 以10%精度来说&#xff1a;&#xff08;数值少&#xff0c;好算&am…

大专非科班转码成功自白

大专非科班转码成功自白 文章目录 大专非科班转码成功自白初步学习进阶学习提供阶段面试阶段总结 2023年是博主从业18年以来找工作最难的一年。但程序员这个行业还是被很多毕业生青睐。就业相对比较好&#xff0c;收入相对比较高&#xff0c;虽然面临996&#xff0c;依然给很多…

网络安全--linux下Nginx安装以及docker验证标签漏洞

目录 一、Nginx安装 二、docker验证标签漏洞 一、Nginx安装 1.首先创建Nginx的目录并进入&#xff1a; mkdir /soft && mkdir /soft/nginx/cd /soft/nginx/ 2.下载Nginx的安装包&#xff0c;可以通过FTP工具上传离线环境包&#xff0c;也可通过wget命令在线获取安装包…

从零实战SLAM-第九课(后端优化)

在七月算法报的班&#xff0c;老师讲的蛮好。好记性不如烂笔头&#xff0c;关键内容还是记录一下吧&#xff0c;课程入口&#xff0c;感兴趣的同学可以学习一下。 --------------------------------------------------------------------------------------------------------…

uniapp的UI框架组件库——uView

在写uniapp项目时候&#xff0c;官方所推荐的样式库并不能满足日常的需求&#xff0c;也不可能自己去写相应的样式&#xff0c;费时又费力&#xff0c;所以我们一般会去使用第三方的组件库UI&#xff0c;就像vue里我们所熟悉的elementUI组件库一样的道理&#xff0c;在uniapp中…

预测算法系列5—核极限学习机KELM及其实现(Matlab)

回归&#xff1a; 分类&#xff1a; 在上一篇文章中我介绍了极限学习机ELM的实现和优化&#xff0c;极限学习机虽然具有训练速度快、复杂度低、克服了传统梯度算法的局部极小、过拟合和学习率的选择不合适等优点&#xff0c;但在比较复杂的分类、回归等非线性模式识别任务往往…

DaVinci Resolve Studio 18 for Mac 达芬奇调色

DaVinci Resolve Studio 18是一款专业的视频编辑和调色软件&#xff0c;适用于电影、电视节目、广告等各种视觉媒体的制作。它具有完整的后期制作功能&#xff0c;包括剪辑、调色、特效、音频处理等。 以下是DaVinci Resolve Studio 18的主要特点&#xff1a; - 提供了全面的视…