QStandardItemModel的使用
实现功能:
打开一个文本文件,该文件为二维数据文件,通过字符串处理获取表头和各行各列数据,导入到QStandardItemModel数据模型
编辑修改数据模型的数据
设置数据模型中某项的不同角色的数据
通过QItemSelectionModel获取视图组件上当前单元格
将数据模型中的数据显示到QPlainTextEdit组件中
将修改后的数据模型另存为一个文本文件
mainwindow.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QStandardItemModel>
#include <QItemSelectionModel>
namespace Ui {
class MainWindow;
}
#define FixedColumCount 6 //固定列数为6
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QLabel *LabCurFile;//表示当前文件
QLabel *LabCellPos;//当前单元格行列号
QLabel *LabCellText;//当前单元格内容
QStandardItemModel *theModel;//加入头文件<QStandardItemModel>
//数据模型
QItemSelectionModel *theSelection;//加入头文件<QItemSelectionModel>
//选择数据模型
void iniModelFromStringList(QStringList&);//从StringList初始化数据模型
private slots:
//自定义槽函数
void on_currentChanged(const QModelIndex ¤t,const QModelIndex &previous);
void on_actOpen_triggered();
void on_actAppend_triggered();
void on_actInsert_triggered();
void on_actDelete_triggered();
void on_actAlignLeft_triggered();
void on_actAlignCenter_triggered();
void on_actAlignRight_triggered();
void on_actFontBold_triggered();
void on_actFontBold_triggered(bool checked);
void on_actModelData_triggered();
void on_actSave_triggered();
};
#endif // MAINWINDOW_H
mainwindow.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTableView>
#include <QFileDialog>
#include <QTextStream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//进行界面初始化,数据模型和选择模型的创建,信号与槽的关联
setCentralWidget(ui->splitter);
theModel=new QStandardItemModel(2,FixedColumCount,this);//2*6的数据模型
theSelection=new QItemSelectionModel(theModel);//选择模型
connect(theSelection,SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(on_currentChanged(QModelIndex,QModelIndex)));
//Selection的currentChanged信号()与on_currentChanged()关联
ui->tableView->setModel(theModel);
ui->tableView->setSelectionModel(theSelection);
ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);//允许选中多行
ui->ta