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