使用QStandardItemModel、QItemSelectionModel 绑定到tableView

news2024/10/5 10:25:43

1、使用QStandardItemModel、QItemSelectionModel   绑定到tableView,展示tableView的新增、插入,删除 、生成文档操作;

2、文本文件的读写

3、遍历QStandardItemModel

4、遍历 QItemSelectionModel

布局

  .h

#ifndef TABLEMODELVIEWEXAMPLE_H
#define TABLEMODELVIEWEXAMPLE_H

#include <QMainWindow>
#include <QLabel>
#include <QStandardItemModel>
#include <QItemSelectionModel>

#define     FixedColumnCount    6       //文件固定6列


namespace Ui {
class tableModelViewExample;
}

class tableModelViewExample : public QMainWindow
{
    Q_OBJECT
private:
    QLabel *labCurFile;
    QLabel *labCellPos;
    QLabel *labCellText;

    QStandardItemModel *m_model;
    QItemSelectionModel *m_selection;

    void iniModelData(QStringList&);

    void openDataFile(QString aFileName);

    void setSelectionItemAlign(Qt::Alignment atextAlignment);
public:
    explicit tableModelViewExample(QWidget *parent = nullptr);
    ~tableModelViewExample();

private slots:
    void do_currentChanged(const QModelIndex &current, const QModelIndex &previous);



    void on_actOpen_triggered();

    void on_actAppend_triggered();

    void on_actDelete_triggered();

    void on_actInsert_triggered();

    void on_actModelData_triggered();

    void on_actAlignLeft_triggered();

    void on_actAlignLeft_triggered(bool checked);

    void on_actAlignCenter_triggered(bool checked);

    void on_actAlignRight_triggered(bool checked);

    void on_actFontBold_triggered(bool checked);

    void on_actSave_triggered();

private:
    Ui::tableModelViewExample *ui;
};

#endif // TABLEMODELVIEWEXAMPLE_H

 

.cpp

 

#include "tablemodelviewexample.h"
#include "ui_tablemodelviewexample.h"

#include <QFileDialog>
#include <QTextStream>
#include <QRegularExpression>

void tableModelViewExample::openDataFile(QString aFileName)
{
    QStringList aFileContent;
    QFile aFile(aFileName);
    if(aFile.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QTextStream aStream(&aFile);
        ui->plainTextEdit->clear();
        while(!aStream.atEnd())
        {
            QString str=aStream.readLine();
            ui->plainTextEdit->appendPlainText(str);
            aFileContent.append(str);
        }
        aFile.close();

        labCurFile->setText("当前文件:"+aFileName);
        ui->actAppend->setEnabled(true);
        ui->actInsert->setEnabled(true);
        ui->actDelete->setEnabled(true);
        ui->actSave->setEnabled(true);

        iniModelData(aFileContent);
    }
}

void tableModelViewExample::iniModelData(QStringList &aFileContent)
{
    int row = aFileContent.size();
    m_model->setRowCount(row-1);

    QString header=aFileContent.at(0);
    QStringList headerList = header.split(QRegularExpression("\\s+"),Qt::SkipEmptyParts);
    m_model->setHorizontalHeaderLabels(headerList);

    //设置表格数据
    int j;
    QStandardItem *aItem;
    for(int i=1;i<row;i++)
    {
        QString aLineText = aFileContent.at(i);
        QStringList tmpList =
            aLineText.split(QRegularExpression("\\s+"),Qt::SkipEmptyParts);
        for(j=0;j<FixedColumnCount-1;j++)
        {
            aItem= new QStandardItem(tmpList.at(j));
            m_model->setItem(i-1,j,aItem);
        }
        aItem=new QStandardItem(headerList.at(j));//最后一列
        aItem->setCheckable(true);
        aItem->setBackground(QBrush(Qt::yellow));
        if(tmpList.at(j)=="0")
            aItem->setCheckState(Qt::Unchecked);
        else
            aItem->setCheckState(Qt::Checked);
        m_model->setItem(i-1,j,aItem);
    }



}

tableModelViewExample::tableModelViewExample(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::tableModelViewExample)
{
    ui->setupUi(this);
    //初始化数据
    m_model= new QStandardItemModel(2,FixedColumnCount,this);
    m_selection = new QItemSelectionModel(m_model,this);

    connect(m_selection,&QItemSelectionModel::currentChanged,
            this,&tableModelViewExample::do_currentChanged);

    ui->tableView->setModel(m_model);
    ui->tableView->setSelectionModel(m_selection);
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);

    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);

    // setCentralWidget(ui->sp);

    labCurFile = new QLabel("当前文件:",this);
    labCurFile->setMinimumWidth(200);

    labCellPos= new QLabel("当前单元格:",this);
    labCellPos->setMinimumWidth(180);
    labCellPos->setAlignment(Qt::AlignHCenter);

    labCellText = new QLabel("单元格内容",this);
    labCellText->setMinimumWidth(150);

    ui->statusbar->addWidget(labCurFile);
    ui->statusbar->addWidget(labCellPos);
    ui->statusbar->addWidget(labCellText);

}

tableModelViewExample::~tableModelViewExample()
{
    delete ui;
}

void tableModelViewExample::do_currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);
    if(current.isValid())
    {
        labCellPos->setText(QString::asprintf("当前单元格:%d 行,%d列",
                                              current.row(),
                                              current.column()));

        QStandardItem *item = m_model->itemFromIndex(current);
        labCellText->setText("单元格内容:"+item->text());

        QFont font = item->font();
        ui->actFontBold->setChecked(font.bold());

    }
}

void tableModelViewExample::on_actOpen_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString fileName= QFileDialog::getOpenFileName(this,
                                                    "打开文件",
                                                    curPath,
                                                    "数据文件(*.txt);;所有文件(*.*)");
    if(fileName.isEmpty())
        return;

    openDataFile(fileName);

}


void tableModelViewExample::on_actAppend_triggered()
{
    QList<QStandardItem*> itemList;
    QStandardItem *item;
    for (int  i= 0;  i< FixedColumnCount-1; i++) {
        item= new QStandardItem("0");
        itemList<<item;
    }
    QString str= m_model->headerData(m_model->columnCount()-1,
                                      Qt::Horizontal
                                      ,Qt::DisplayRole).toString();
    item= new QStandardItem(str);
    item->setCheckable(true);
    itemList<<item;

    m_model->insertRow(m_model->rowCount(),itemList);
    QModelIndex curIndex = m_model->index(m_model->rowCount()-1,0);
    m_selection->clearSelection();
    m_selection->setCurrentIndex(curIndex,QItemSelectionModel::Select);//设置当前行

}


void tableModelViewExample::on_actDelete_triggered()
{
    QModelIndex curIndex= m_selection->currentIndex();

    if(curIndex.row()== m_model->rowCount()-1)
        m_model->removeRow(curIndex.row());
    else
    {
        m_model->removeRow(curIndex.row());
        m_selection->setCurrentIndex(curIndex,QItemSelectionModel::Select);
    }
}


void tableModelViewExample::on_actInsert_triggered()
{
    QList<QStandardItem*> itemList;
    QStandardItem *item;
    for(int i=0;i<FixedColumnCount-1;i++)//最后一列单独设置
    {
        item = new QStandardItem("0");
        itemList<<item;
    }
    QString str;

    str=m_model->headerData(m_model->columnCount()-1,Qt::Horizontal,Qt::DisplayRole).toString();
    item = new QStandardItem(str);
    item->setCheckable(true);
    itemList<<item;

    QModelIndex curIndex = m_selection->currentIndex();
    m_model->insertRow(curIndex.row(),itemList);//m_model->rowCount()-1
    m_selection->clearSelection();
    m_selection->setCurrentIndex(curIndex,QItemSelectionModel::Select);


}


void tableModelViewExample::on_actModelData_triggered()
{//模型数据展示到 text控件
    ui->plainTextEdit->clear();
    QStandardItem *item ;
    QString str;
    for(int i=0;i<m_model->columnCount();i++)//列
    {
        item=m_model->horizontalHeaderItem(i);
        str+= item->text()+"\t";
    }
    ui->plainTextEdit->appendPlainText(str);

    for(int i=0;i<m_model->rowCount();i++)//列
    {
        str="";
        for(int j=0;j<m_model->columnCount()-1;j++)
        {
            item=m_model->item(j,j);
            str+=item->text()+"\t";
        }
        item = m_model->item(i,FixedColumnCount-1);//最后一列
        if(item->checkState()== Qt::Checked)
            str+="1";
        else
            str+="0";

        ui->plainTextEdit->appendPlainText(str);
    }
}


void tableModelViewExample::on_actSave_triggered()
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString fileName = QFileDialog::getSaveFileName(this
                                                    ,tr("选择一个文件")
                                                    ,curPath
                                                    ,"数据文件(*.txt);;所有文件(*。*)");
    if(fileName.isEmpty())
        return;

    QFile aFile(fileName);
    if(!aFile.open(QIODevice::ReadWrite
                   |QIODevice::Text
                   |QIODevice::Truncate
                   ))
        return;

    QTextStream stream(&aFile);
    QStandardItem *item;
    QString str;
    ui->plainTextEdit->clear();
    for(int i=0;i<m_model->columnCount();i++)
    {
        item = m_model->horizontalHeaderItem(i);
        str+= item->text()+"\t\t";
    }
    stream<<str<<"\n";
    ui->plainTextEdit->appendPlainText(str);

    for(int i=0;i<m_model->rowCount()-1;i++)
    {
        str ="";
        for(int j=0;j<m_model->columnCount()-1;j++)
        {
            item= m_model->item(i,j);
            str+= item->text()+"\t\t";
        }
        item= m_model->item(i,FixedColumnCount-1);
        if(item->checkState()== Qt::Checked)
            str+="1";
        else
            str+="0";

        stream<<str<<"\n";
        ui->plainTextEdit->appendPlainText(str);
    }
}

//处理文本居左居右居中的统一实现方法
void tableModelViewExample::setSelectionItemAlign(Qt::Alignment atextAlignment)
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList selectedIndexs= m_selection->selectedIndexes();
    QModelIndex index;
    QStandardItem *item;
    for(int i=0;i<selectedIndexs.count();i++)
    {
        index = selectedIndexs.at(i);
        item = m_model->itemFromIndex(index);
        item->setTextAlignment(atextAlignment);
    }
}

void tableModelViewExample::on_actAlignLeft_triggered()
{
    this->setSelectionItemAlign(Qt::AlignVCenter|Qt::AlignLeft);
}


void tableModelViewExample::on_actAlignLeft_triggered(bool checked)
{
    this->setSelectionItemAlign(Qt::AlignVCenter|Qt::AlignLeft);
}


void tableModelViewExample::on_actAlignCenter_triggered(bool checked)
{
    this->setSelectionItemAlign(Qt::AlignVCenter|Qt::AlignHCenter);
}


void tableModelViewExample::on_actAlignRight_triggered(bool checked)
{
    this->setSelectionItemAlign(Qt::AlignVCenter|Qt::AlignRight);
}


void tableModelViewExample::on_actFontBold_triggered(bool checked)
{
    if(!m_selection->hasSelection())
        return;
    QModelIndexList selectedIndexs= m_selection->selectedIndexes();
    QModelIndex index;
    QStandardItem *item;
    for(int i=0;i<selectedIndexs.count();i++)
    {
        index = selectedIndexs.at(i);
        item = m_model->itemFromIndex(index);
        QFont font = item->font();
        font.setBold(checked);
        item->setFont(font);
    }
}


结果

总结
 

 //遍历QStandardItemModel的列头

for(int i=0;i<m_model->columnCount();i++)//列
    {
        item=m_model->horizontalHeaderItem(i); //遍历QStandardItemModel的列头
        str+= item->text()+"\t";
    }

 //QItemSelectionModel的获取选中的单元格

if(!m_selection->hasSelection())//QItemSelectionModel的获取选中的单元格
        return;
    QModelIndexList selectedIndexs= m_selection->selectedIndexes();
    QModelIndex index;
    QStandardItem *item;
    for(int i=0;i<selectedIndexs.count();i++)
    {
        index = selectedIndexs.at(i);
        item = m_model->itemFromIndex(index);
        item->setTextAlignment(atextAlignment);
    }

 //给QTableView 设置 数据模型,单元格选择模型

    ui->tableView->setModel(m_model);  //设置数据模型
    ui->tableView->setSelectionModel(m_selection); //设置选择模型
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);

//使用正则表达式, 分割split  得到行的单元格 

QStringList tmpList =
            aLineText.split(QRegularExpression("\\s+"),Qt::SkipEmptyParts);

 //每个单元格里面放的是QStandardItem*,插入行用一个列表插入QList<QStandardItem*> itemList

QList<QStandardItem*> itemList;
    QStandardItem *item;
    for (int  i= 0;  i< FixedColumnCount-1; i++) {
        item= new QStandardItem("0");
        itemList<<item;
    }
    QString str= m_model->headerData(m_model->columnCount()-1,
                                      Qt::Horizontal
                                      ,Qt::DisplayRole).toString();
    item= new QStandardItem(str);
    item->setCheckable(true);
    itemList<<item;

    m_model->insertRow(m_model->rowCount(),itemList);

 //removeRow 使用 curIndex.row()来删除

 QModelIndex curIndex= m_selection->currentIndex();

    if(curIndex.row()== m_model->rowCount()-1)
        m_model->removeRow(curIndex.row());

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

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

相关文章

windows机器通过证书方式登录linux主机

1. 正常连接需要输入密码 ssh root1.1.1.1 2. 在Windows上生成SSH密钥对&#xff08;如果你还没有的话&#xff09;&#xff1a; ssh-keygen 3. scp将id_rsa.pub传输到对应的主机 4.对应机器上查看 5.从windows上免密登录

LiveNVR监控流媒体Onvif/RTSP用户手册-分屏展示:分组、轮播、四分屏、九分屏、十六分屏

LiveNVR监控流媒体Onvif/RTSP用户手册-分屏展示:分组、轮播、四分屏、九分屏、十六分屏 1、分屏展示1.1、选择通道1.2、多分屏1.3、分组1.4、轮播 2、RTSP/HLS/FLV/RTMP拉流Onvif流媒体服务 1、分屏展示 1.1、选择通道 1.2、多分屏 支持 单屏、四分屏、九分屏、十六分屏 ![请添…

昇思25天学习打卡营第16天|ShuffleNet图像分类

学AI还能赢奖品&#xff1f;每天30分钟&#xff0c;25天打通AI任督二脉 (qq.com) ShuffleNet图像分类 当前案例不支持在GPU设备上静态图模式运行&#xff0c;其他模式运行皆支持。 ShuffleNet网络介绍 ShuffleNetV1是旷视科技提出的一种计算高效的CNN模型&#xff0c;和Mobile…

4D 生物打印智能生物墨水需要具备哪些关键特性?

4D 生物打印智能生物墨水需要具备哪些关键特性&#xff1f; 1. 可打印性 (Printability) MEB&#xff1a;生物墨水需要具有良好的流变学特性&#xff0c;例如高粘度、剪切稀化行为和触变性。打印参数&#xff08;如喷嘴直径、打印速度和层厚&#xff09;会影响打印性能。 喷…

Golang 依赖注入设计哲学|12.6K 的依赖注入库 wire

一、前言 线上项目往往依赖非常多的具备特定能力的资源&#xff0c;如&#xff1a;DB、MQ、各种中间件&#xff0c;以及随着项目业务的复杂化&#xff0c;单一项目内&#xff0c;业务模块也逐渐增多&#xff0c;如何高效、整洁管理各种资源十分重要。 本文从“术”层面&#…

游戏AI的创造思路-技术基础-自然语言处理

自然语言处理-可以对游戏AI特别是RPG类、语言类游戏进行“附魔”&#xff0c;开发出“随机应变”和你聊天的“女友”、“队友”或者是根据你定义的文本库来用接近自然语言的生成“语言”&#xff0c;推动游戏情景在受控范围内前进 目录 1. 自然语言处理定义 2. 发展历史 3. …

【配置网络和使用ssh服务】

文章目录 一、配置文件二、配置网络1.使用系统菜单配置网络2.通过网卡配置文件配置网络3.使用图形界面配置网络4.使用nmcli命令配置网络 三、配置远程控制服务1.配置sshd服务2.安全密钥验证3.远程传输命令 一、配置文件 跟网络有关的主要配置文件如下&#xff1a; /etc/host.c…

RS232、RS485、RS422、RS423、RS449的联系与区别

这些标准&#xff08;RS232、RS485、RS422、RS423、RS449&#xff09;都涉及将并行数据转换为串行数据进行传输&#xff1a; 数据转换过程&#xff1a; 在发送端&#xff0c;并行数据&#xff08;通常是字节或字&#xff09;被转换成串行比特流。 在接收端&#xff0c;串行比特…

CH552G使用的pwm出现的问题,及设置

输出pwm的频率周期很不准确 可能是因为没有外部晶振的稳定晶振周期有关。 使用的示波器出现操作失误 在使用小型示波器的过程中发现集成了信号发生器和示波器的连接端口是不同的。刚开始把示波器测试口错插入了信号发生器的接口&#xff0c;困扰好一会儿&#xff0c;幸好用一…

Zabbix 配置WEB监控

Zabbix WEB监控介绍 在Zabbix中配置Web监控&#xff0c;可以监控网站的可用性和响应时间。Zabbix提供了内置的Web监控功能&#xff0c;通过配置Web场景&#xff08;Web Scenario&#xff09;&#xff0c;可以监控HTTP/HTTPS协议下的Web服务。 通过Zabbix的WEB监控可以监控网站…

超声波气象站的工作原理

TH-CQX5超声波气象站中的超声波技术是其核心工作原理之一&#xff0c;以下是关于超声波气象站中超声波的详细解释&#xff1a;超声波是一种频率高于人耳能听到的声音频率范围的声波&#xff0c;通常指频率在20kHz以上的声波。超声波具有较短的波长和强的穿透能力&#xff0c;能…

vue安装+测试

1.下载node.js 在浏览器中打开nodejs官网https://nodejs.org/zh-cn/ &#xff0c;选择需要的版本 2.检查nodejs是否安装成功 打开cmd&#xff0c;输入命令 node -v PS C:\Users\neuer> node -v v20.15.03.安装cnpm 遇到npm ERR! code CERT_HAS_EXPIRED问题 清除npm缓存 n…

【TS】交叉类型 和 联合类型

文章目录 1. 交叉类型&#xff08;Intersection Types&#xff09;2. 联合类型&#xff08;Union Types&#xff09; 1. 交叉类型&#xff08;Intersection Types&#xff09; 交叉类型将多个类型合并为一个类型&#xff0c;这个新类型具有所有类型的特性。使用 & 符号来定…

妙手ERP接入Miravia,支持高效上货、批量订单处理

欧洲电子商务市场目前已经成为了中国跨境电商出口的“新蓝海”。放眼欧洲&#xff0c;西班牙电商市场规模并不算大&#xff0c;但却是增长率最高的市场之一&#xff0c;并且正在追赶其他电商市场。  据Statista的调查数据显示&#xff0c;2024年初西班牙的电商收入将达到355亿…

python自动化办公-往ppt插入图片

目录 思路 代码 代码效果 思路 1、导包 2、打开ppt 3、新增1张幻灯片&#xff0c;选择自己需要的版式 4、输入标题 5、设置好图片的位置和大小&#xff0c;插入准备好的图片 6、保存文件 代码 from pptx import Presentation from pptx.util import Inches # 打开pp…

【C语言入门】初识C语言:掌握编程的基石

&#x1f4dd;个人主页&#x1f339;&#xff1a;Eternity._ ⏩收录专栏⏪&#xff1a;C语言 “ 登神长阶 ” &#x1f921;往期回顾&#x1f921;&#xff1a;C语言入门 &#x1f339;&#x1f339;期待您的关注 &#x1f339;&#x1f339; ❀C语言入门 &#x1f4d2;1. 选择…

c->c++(二):class

本文主要探讨C类的相关知识。 构造和析构函数 构造函数(可多个)&#xff1a;对象产生时调用初始化class属性、分配class内部需要的动态内存 析构函数&#xff08;一个&#xff09;&#xff1a;对对象消亡时调用回收分配动态内存 C提供默认构造和析构,…

使用pdf.js在Vue、React中预览Pdf文件,支持PC端、移动端

&#x1f4dd; 使用背景 在前端开发中&#xff0c;有时候我们需要进行pdf文件的预览操作&#xff0c;通过在网上查询&#xff0c;基本都是一下几种常见的预览pdf文件的方法&#xff1a; 实现方案效果HTML 标签iframe 标签iOS&#xff1a;只能展示第一页&#xff0c;多页不能展…

Windows安全认证机制——Windows常见协议

一.LLMNR协议 1.LLMNR简介 链路本地多播名称解析&#xff08;LLMNR&#xff09;是一个基于域名系统&#xff08;DNS&#xff09;数据包格式的协议&#xff0c;使用此协议可以解析局域网中本地链路上的主机名称。它可以很好地支持IPv4和IPv6&#xff0c;是仅次于DNS解析的名称…

63、基于深度学习网络的数字分类(matlab)

1、基于深度学习网络的数字分类的原理及流程 基于深度学习网络的数字分类是一种常见的机器学习任务&#xff0c;通常使用的是卷积神经网络&#xff08;CNN&#xff09;来实现。下面是其原理及流程的简要说明&#xff1a; 数据收集&#xff1a;首先&#xff0c;需要收集包含数字…