qfile 创建文件_Qt之二进制文件读写

点击上方“Qt学视觉”,选择“星标”公众号重磅干货,第一时间送达

想要学习的同学们还请认真阅读每篇文章,相信你一定会有所收获

除了文本文件之外,其他需要按照一定的格式定义读写的文件都称为二进制文件,每种格式的二进制文件都有自己的格式定义,写入数据时按照一定的顺序写入,读出时也按照相应的顺序读出

Qt使用QFile和QDataStream进行二进制数据文件的读写,QFile负责文件的IO设备接口,即与文件的物理交互,QDataStream以数据流的方式读取文件内容或写入文件内容

紧接着上一节的界面往上加这节的界面

8af8c38d46b6298ceae33d7e6d0f5658.png

fa9a99fedd930ccc096a8d81587cbaf4.png

头文件

#pragma once#include #include "ui_QGuiFileSys.h"#include "QComboBoxDelegate.h"#include "QFloatSpinDelegate.h"#include "QIntSpinDelegate.h"#include #include #include #include #define     FixedColumnCount    6       //文件固定6行class QGuiFileSys : public QMainWindow{       Q_OBJECTpublic:       QGuiFileSys(QWidget *parent = Q_NULLPTR);       ~QGuiFileSys();private:       Ui::QGuiFileSys ui;private:       bool openTextByIODevice(const QString& aFileName);       bool saveTextByIODevice(const QString& aFileName);       bool openTextByStream(const QString& aFileName);       bool saveTextByStream(const QString& aFileName);private slots:       void actOpenIODevice_triggered();       void actSaveIODevice_triggered();       void actOpenTextStream_triggered();       void actSaveTextStream_triggered();private:       //用于状态栏的信息显示       QLabel* LabCellPos;    //当前单元格行列号       QLabel* LabCellText;   //当前单元格内容       QIntSpinDelegate    intSpinDelegate; //整型数       QFloatSpinDelegate  floatSpinDelegate; //浮点数       QComboBoxDelegate   comboBoxDelegate; //列表选择       QStandardItemModel* theModel;//数据模型       QItemSelectionModel* theSelection;//Item选择模型       void resetTable(int aRowCount);  //表格复位,设定行数       bool saveDataAsStream(QString& aFileName);//将数据保存为数据流文件       bool openDataAsStream(QString& aFileName);//读取数据流文件       bool saveBinaryFile(QString& aFileName);//保存为二进制文件       bool openBinaryFile(QString& aFileName);//打开二进制文件private slots:       void theSelection_currentChanged(const QModelIndex& current, const  QModelIndex& previous);       void actTabReset_triggered();       void actOpenStm_triggered();       void actSaveStm_triggered();       void actOpenBin_triggered();       void actSaveBin_triggered();       void actAppend_triggered();       void actInsert_triggered();       void actDelete_triggered();       void actAlignLeft_triggered();       void actAlignCenter_triggered();       void actAlignRight_triggered();       void actFontBold_triggered(bool checked);}

源文件

#include "QGuiFileSys.h"#include #include #include #include #include #include #include #include #include #include #pragma execution_character_set("utf-8")QGuiFileSys::QGuiFileSys(QWidget *parent)    : QMainWindow(parent){    ui.setupUi(this);    connect(ui.actOpenIODevice, SIGNAL(triggered()), this, SLOT(actOpenIODevice_triggered()));    connect(ui.actSaveIODevice, SIGNAL(triggered()), this, SLOT(actSaveIODevice_triggered()));    connect(ui.actOpenTextStream, SIGNAL(triggered()), this, SLOT(actOpenTextStream_triggered()));    connect(ui.actSaveTextStream, SIGNAL(triggered()), this, SLOT(actSaveTextStream_triggered()));    connect(ui.actTabReset, SIGNAL(triggered()), this, SLOT(actTabReset_triggered()));    connect(ui.actOpenStm, SIGNAL(triggered()), this, SLOT(actOpenStm_triggered()));    connect(ui.actSaveStm, SIGNAL(triggered()), this, SLOT(actSaveStm_triggered()));    connect(ui.actOpenBin, SIGNAL(triggered()), this, SLOT(actOpenBin_triggered()));    connect(ui.actSaveBin, SIGNAL(triggered()), this, SLOT(actSaveBin_triggered()));    connect(ui.actAppend, SIGNAL(triggered()), this, SLOT(actAppend_triggered()));    connect(ui.actInsert, SIGNAL(triggered()), this, SLOT(actInsert_triggered()));    connect(ui.actDelete, SIGNAL(triggered()), this, SLOT(actDelete_triggered()));    connect(ui.actAlignLeft, SIGNAL(triggered()), this, SLOT(actAlignLeft_triggered()));    connect(ui.actAlignCenter, SIGNAL(triggered()), this, SLOT(actAlignCenter_triggered()));    connect(ui.actAlignRight, SIGNAL(triggered()), this, SLOT(actAlignRight_triggered()));    connect(ui.actFontBold, SIGNAL(triggered(bool)), this, SLOT(actFontBold_triggered(bool)));    theModel = new QStandardItemModel(5, FixedColumnCount, this); //创建数据模型    QStringList     headerList;    headerList << "Depth" << "Measured Depth" << "Direction" << "Offset" << "Quality" << "Sampled";    theModel->setHorizontalHeaderLabels(headerList); //设置表头文字    theSelection = new QItemSelectionModel(theModel);//Item选择模型    connect(theSelection, SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)),        this, SLOT(theSelection_currentChanged(const QModelIndex&, const QModelIndex&)));    //为tableView设置数据模型    ui.tableView->setModel(theModel); //设置数据模型    ui.tableView->setSelectionModel(theSelection);//设置选择模型    //为各列设置自定义代理组件    ui.tableView->setItemDelegateForColumn(0, &intSpinDelegate);  //测深,整数    ui.tableView->setItemDelegateForColumn(1, &floatSpinDelegate);  //浮点数    ui.tableView->setItemDelegateForColumn(2, &floatSpinDelegate); //浮点数    ui.tableView->setItemDelegateForColumn(3, &floatSpinDelegate); //浮点数    ui.tableView->setItemDelegateForColumn(4, &comboBoxDelegate); //Combbox选择型    resetTable(5); //表格复位    //创建状态栏组件    LabCellPos = new QLabel("当前单元格:", this);    LabCellPos->setMinimumWidth(180);    LabCellPos->setAlignment(Qt::AlignHCenter);    LabCellText = new QLabel("单元格内容:", this);    LabCellText->setMinimumWidth(200);    ui.statusBar->addWidget(LabCellPos);    ui.statusBar->addWidget(LabCellText);}QGuiFileSys::~QGuiFileSys(){}bool QGuiFileSys::openTextByIODevice(const QString& aFileName){    //用IODevice方式打开文本文件    QFile aFile(aFileName);    //aFile.setFileName(aFileName);    if (!aFile.exists()) //文件不存在        return false;    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))        return false;    //ui.textEditDevice->setPlainText(aFile.readAll());    ui.textEditDevice->clear();    while (!aFile.atEnd())    {        QByteArray line = aFile.readLine();//自动添加 \n        QString str=QString::fromLocal8Bit(line); //从字节数组转换为字符串        str.truncate(str.length()-1); //去除结尾增加的空行        ui.textEditDevice->appendPlainText(str);    }    aFile.close();    ui.tabWidget->setCurrentIndex(0);    return  true;}bool QGuiFileSys::saveTextByIODevice(const QString& aFileName){    //用IODevice方式保存文本文件    QFile aFile(aFileName);    //aFile.setFileName(aFileName);    if (!aFile.open(QIODevice::WriteOnly | QIODevice::Text))        return false;    QString str = ui.textEditDevice->toPlainText();//整个内容作为字符串    QByteArray  strBytes = str.toUtf8();//转换为字节数组    //QByteArray  strBytes=str.toLocal8Bit();    aFile.write(strBytes, strBytes.length());  //写入文件    aFile.close();    ui.tabWidget->setCurrentIndex(0);    return  true;}bool QGuiFileSys::openTextByStream(const QString& aFileName){    //用 QTextStream打开文本文件    QFile   aFile(aFileName);    if (!aFile.exists()) //文件不存在        return false;    if (!aFile.open(QIODevice::ReadOnly | QIODevice::Text))        return false;    QTextStream aStream(&aFile); //用文本流读取文件    //aStream.setAutoDetectUnicode(true); //自动检测Unicode,才能正常显示文档内的汉字    ui.textEditStream->setPlainText(aStream.readAll());    //ui.textEditStream->clear();//清空    //while (!aStream.atEnd())    //{    //    str = aStream.readLine();//读取文件的一行    //    ui.textEditStream->appendPlainText(str); //添加到文本框显示    //}    aFile.close();//关闭文件    ui.tabWidget->setCurrentIndex(1);    return  true;}bool QGuiFileSys::saveTextByStream(const QString& aFileName){    //用QTextStream保存文本文件    QFile aFile(aFileName);    if (!aFile.open(QIODevice::WriteOnly | QIODevice::Text))        return false;    QTextStream aStream(&aFile); //用文本流读取文件    //aStream.setAutoDetectUnicode(true); //自动检测Unicode,才能正常显示文档内的汉字    QString str = ui.textEditStream->toPlainText(); //转换为字符串    aStream << str; //写入文本流    //QTextDocument   *doc;       //文本对象    //QTextBlock      textLine;   //文本中的一段    //doc=ui.textEditStream->document(); //QPlainTextEdit 的内容保存在一个 QTextDocument 里    //int cnt=doc->blockCount();//QTextDocument分块保存内容,文本文件就是硬回车符是一个block,    //QString str;    //for (int i=0; i    //{    //     textLine=doc->findBlockByNumber(i);//用blobk编号获取block,就是获取一行    //     str=textLine.text(); //转换为文本,末尾无\n    //     aStream<    //}    aFile.close();//关闭文件    return  true;}void QGuiFileSys::actOpenIODevice_triggered(){    //获取系统当前目录    QString curpath = QDir::currentPath();    //调用打开文件对话框打开一个文件    QString aFileName = QFileDialog::getOpenFileName(this, "打开一个文件", curpath,        "程序文件(*.h *cpp);;文本文件(*.txt);;所有文件(*.*)");    if (aFileName.isEmpty())        return; //如果未选择文件,退出    openTextByIODevice(aFileName); //打开文件}void QGuiFileSys::actSaveIODevice_triggered(){    QString curpath = QDir::currentPath();//获取系统当前目录    QString dlgTitle = "另存为一个文件"; //对话框标题    QString filter = "h文件(*.h);;c++文件(*.cpp);;文本文件(*.txt);;所有文件(*.*)"; //文件过滤器    QString aFileName = QFileDialog::getSaveFileName(this, dlgTitle, curpath, filter);    if (aFileName.isEmpty())        return;    saveTextByIODevice(aFileName);}void QGuiFileSys::actOpenTextStream_triggered(){    QString curpath = QDir::currentPath();//获取系统当前目录    //调用打开文件对话框打开一个文件    QString aFileName = QFileDialog::getOpenFileName(this, "打开一个文件", curpath,        "程序文件(*.h *cpp);;文本文件(*.txt);;所有文件(*.*)");    if (aFileName.isEmpty())        return; //如果未选择文件,退出    openTextByStream(aFileName); //打开文件}void QGuiFileSys::actSaveTextStream_triggered(){    QString curpath = QDir::currentPath();//获取系统当前目录    QString dlgTitle = "另存为一个文件"; //对话框标题    QString filter = "h文件(*.h);;c++文件(*.cpp);;文本文件(*.txt);;所有文件(*.*)"; //文件过滤器    QString aFileName = QFileDialog::getSaveFileName(this, dlgTitle, curpath, filter);    if (aFileName.isEmpty())        return;    saveTextByStream(aFileName);}//表格复位,设定行数void QGuiFileSys::resetTable(int aRowCount){    //表格复位,先删除所有行,再设置新的行数,表头不变    //QStringList     headerList;    //headerList<    //theModel->setHorizontalHeaderLabels(headerList); //设置表头文字    theModel->removeRows(0, theModel->rowCount()); //删除所有行    theModel->setRowCount(aRowCount);//设置新的行数    QString str = theModel->headerData(theModel->columnCount() - 1,        Qt::Horizontal, Qt::DisplayRole).toString();    for (int i = 0; i < theModel->rowCount(); i++)    { //设置最后一列        QModelIndex index = theModel->index(i, FixedColumnCount - 1); //获取模型索引        QStandardItem* aItem = theModel->itemFromIndex(index); //获取item        aItem->setCheckable(true);        aItem->setData(str, Qt::DisplayRole);        aItem->setEditable(false); //不可编辑    }}//将数据保存为数据流文件bool QGuiFileSys::saveDataAsStream(QString& aFileName){    //将模型数据保存为Qt预定义编码的数据文件    QFile aFile(aFileName);  //以文件方式读出    if (!(aFile.open(QIODevice::WriteOnly | QIODevice::Truncate)))        return false;    QDataStream aStream(&aFile);    aStream.setVersion(QDataStream::Qt_5_9); //设置版本号,写入和读取的版本号要兼容    qint16  rowCount = theModel->rowCount(); //数据模型行数    qint16  colCount = theModel->columnCount(); //数据模型列数    aStream << rowCount; //写入文件流,行数    aStream << colCount;//写入文件流,列数    //获取表头文字    for (int i = 0; i < theModel->columnCount(); i++)    {        QString str = theModel->horizontalHeaderItem(i)->text();//获取表头文字        aStream << str; //字符串写入文件流,Qt预定义编码方式    }    //获取数据区的数据    for (int i = 0; i < theModel->rowCount(); i++)    {        QStandardItem* aItem = theModel->item(i, 0); //测深        qint16 ceShen = aItem->data(Qt::DisplayRole).toInt();        aStream << ceShen;// 写入文件流,qint16        aItem = theModel->item(i, 1); //垂深        qreal chuiShen = aItem->data(Qt::DisplayRole).toFloat();        aStream << chuiShen;//写入文件流, qreal        aItem = theModel->item(i, 2); //方位        qreal fangWei = aItem->data(Qt::DisplayRole).toFloat();        aStream << fangWei;//写入文件流, qreal        aItem = theModel->item(i, 3); //位移        qreal weiYi = aItem->data(Qt::DisplayRole).toFloat();        aStream << weiYi;//写入文件流, qreal        aItem = theModel->item(i, 4); //固井质量        QString zhiLiang = aItem->data(Qt::DisplayRole).toString();        aStream << zhiLiang;// 写入文件流,字符串        aItem = theModel->item(i, 5); //测井        bool quYang = (aItem->checkState() == Qt::Checked);        aStream << quYang;// 写入文件流,bool型    }    aFile.close();        return true;}//读取数据流文件bool QGuiFileSys::openDataAsStream(QString& aFileName){    //从Qt预定义流文件读入数据    QFile aFile(aFileName);    if (!aFile.open(QIODevice::ReadOnly))        return false;    QDataStream aStream(&aFile);//用文本流读取文件    aStream.setVersion(QDataStream::Qt_5_12);//设置流文件版本号    qint16 rowCount, colCount;    aStream >> rowCount;//读取行数    aStream >> colCount;//读取列数    this->resetTable(rowCount);//表格复位    //读取表头文字    QString str;    for (int i = 0; i < colCount; i++)    {        aStream >> str;//读取表头字符串    }    //获取数据区文字    qint16  ceShen;    qreal  chuiShen;    qreal  fangWei;    qreal  weiYi;    QString  zhiLiang;    bool    quYang;    QStandardItem* aItem;    QModelIndex index;    for (int i = 0; i < rowCount; i++)    {        aStream >> ceShen;//读取测深, qint16        index = theModel->index(i, 0);        aItem = theModel->itemFromIndex(index);        aItem->setData(ceShen, Qt::DisplayRole);        aStream >> chuiShen;//垂深,qreal        index = theModel->index(i, 1);        aItem = theModel->itemFromIndex(index);        aItem->setData(chuiShen, Qt::DisplayRole);        aStream >> fangWei;//方位,qreal        index = theModel->index(i, 2);        aItem = theModel->itemFromIndex(index);        aItem->setData(fangWei, Qt::DisplayRole);        aStream >> weiYi;//位移,qreal        index = theModel->index(i, 3);        aItem = theModel->itemFromIndex(index);        aItem->setData(weiYi, Qt::DisplayRole);        aStream >> zhiLiang;//固井质量,QString        index = theModel->index(i, 4);        aItem = theModel->itemFromIndex(index);        aItem->setData(zhiLiang, Qt::DisplayRole);        aStream >> quYang;//bool        index = theModel->index(i, 5);        aItem = theModel->itemFromIndex(index);        if (quYang)            aItem->setCheckState(Qt::Checked);        else            aItem->setCheckState(Qt::Unchecked);    }    aFile.close();    return true;}//保存为二进制文件bool QGuiFileSys::saveBinaryFile(QString& aFileName){    //保存为纯二进制文件    QFile aFile(aFileName);  //以文件方式读出    if (!(aFile.open(QIODevice::WriteOnly)))        return false;    QDataStream aStream(&aFile); //用文本流读取文件    //aStream.setVersion(QDataStream::Qt_5_9); //无需设置数据流的版本    aStream.setByteOrder(QDataStream::LittleEndian);//windows平台    //aStream.setByteOrder(QDataStream::BigEndian);//QDataStream::LittleEndian    qint16  rowCount = theModel->rowCount();    qint16  colCount = theModel->columnCount();    aStream.writeRawData((char*)&rowCount, sizeof(qint16)); //写入文件流    aStream.writeRawData((char*)&colCount, sizeof(qint16));//写入文件流    //获取表头文字    QByteArray  btArray;    QStandardItem* aItem;    for (int i = 0; i < theModel->columnCount(); i++)    {        aItem = theModel->horizontalHeaderItem(i); //获取表头item        QString str = aItem->text(); //获取表头文字        btArray = str.toUtf8(); //转换为字符数组        aStream.writeBytes(btArray, btArray.length()); //写入文件流,长度uint型,然后是字符串内容    }    //获取数据区文字,    qint8   yes = 1, no = 0; //分别代表逻辑值 true和false    for (int i = 0; i < theModel->rowCount(); i++)    {        aItem = theModel->item(i, 0); //测深        qint16 ceShen = aItem->data(Qt::DisplayRole).toInt();//qint16类型        aStream.writeRawData((char*)&ceShen, sizeof(qint16));//写入文件流        aItem = theModel->item(i, 1); //垂深        qreal chuiShen = aItem->data(Qt::DisplayRole).toFloat();//qreal 类型        aStream.writeRawData((char*)&chuiShen, sizeof(qreal));//写入文件流        aItem = theModel->item(i, 2); //方位        qreal fangWei = aItem->data(Qt::DisplayRole).toFloat();        aStream.writeRawData((char*)&fangWei, sizeof(qreal));        aItem = theModel->item(i, 3); //位移        qreal weiYi = aItem->data(Qt::DisplayRole).toFloat();        aStream.writeRawData((char*)&weiYi, sizeof(qreal));        aItem = theModel->item(i, 4); //固井质量        QString zhiLiang = aItem->data(Qt::DisplayRole).toString();        btArray = zhiLiang.toUtf8();        aStream.writeBytes(btArray, btArray.length()); //写入长度,uint,然后是字符串        //aStream.writeRawData(btArray,btArray.length());//对于字符串,应使用writeBytes()函数        aItem = theModel->item(i, 5); //测井取样        bool quYang = (aItem->checkState() == Qt::Checked); //true or false        if (quYang)            aStream.writeRawData((char*)&yes, sizeof(qint8));        else            aStream.writeRawData((char*)&no, sizeof(qint8));    }    aFile.close();    return true;}//打开二进制文件bool QGuiFileSys::openBinaryFile(QString& aFileName){    //打开二进制文件    QFile aFile(aFileName);  //以文件方式读出    if (!(aFile.open(QIODevice::ReadOnly)))        return false;    QDataStream aStream(&aFile); //用文本流读取文件    //aStream.setVersion(QDataStream::Qt_5_9); //设置数据流的版本    aStream.setByteOrder(QDataStream::LittleEndian);    //aStream.setByteOrder(QDataStream::BigEndian);    qint16  rowCount, colCount;    aStream.readRawData((char*)&rowCount, sizeof(qint16));    aStream.readRawData((char*)&colCount, sizeof(qint16));    this->resetTable(rowCount);    //获取表头文字,但是并不利用    char* buf;    uint strLen;  //也就是 quint32    for (int i = 0; i < colCount; i++)    {        aStream.readBytes(buf, strLen);//同时读取字符串长度,和字符串内容        QString str = QString::fromLocal8Bit(buf, strLen); //可处理汉字    }    //获取数据区数据    QStandardItem* aItem;    qint16  ceShen;    qreal  chuiShen;    qreal  fangWei;    qreal  weiYi;    QString  zhiLiang;    qint8   quYang; //分别代表逻辑值 true和false    QModelIndex index;    for (int i = 0; i < rowCount; i++)    {        aStream.readRawData((char*)&ceShen, sizeof(qint16)); //测深        index = theModel->index(i, 0);        aItem = theModel->itemFromIndex(index);        aItem->setData(ceShen, Qt::DisplayRole);        aStream.readRawData((char*)&chuiShen, sizeof(qreal)); //垂深        index = theModel->index(i, 1);        aItem = theModel->itemFromIndex(index);        aItem->setData(chuiShen, Qt::DisplayRole);        aStream.readRawData((char*)&fangWei, sizeof(qreal)); //方位        index = theModel->index(i, 2);        aItem = theModel->itemFromIndex(index);        aItem->setData(fangWei, Qt::DisplayRole);        aStream.readRawData((char*)&weiYi, sizeof(qreal)); //位移        index = theModel->index(i, 3);        aItem = theModel->itemFromIndex(index);        aItem->setData(weiYi, Qt::DisplayRole);        aStream.readBytes(buf, strLen);//固井质量        zhiLiang = QString::fromLocal8Bit(buf, strLen);        index = theModel->index(i, 4);        aItem = theModel->itemFromIndex(index);        aItem->setData(zhiLiang, Qt::DisplayRole);        aStream.readRawData((char*)&quYang, sizeof(qint8)); //测井取样        index = theModel->index(i, 5);        aItem = theModel->itemFromIndex(index);        if (quYang == 1)            aItem->setCheckState(Qt::Checked);        else            aItem->setCheckState(Qt::Unchecked);    }    aFile.close();    return true;}void QGuiFileSys::theSelection_currentChanged(const QModelIndex& current, const QModelIndex& previous){    Q_UNUSED(previous);    if (current.isValid())    {        LabCellPos->setText(QString::asprintf("当前单元格:%d行,%d列",            current.row(), current.column()));        QStandardItem* aItem;        aItem = theModel->itemFromIndex(current); //从模型索引获得Item        this->LabCellText->setText("单元格内容:" + aItem->text());        QFont   font = aItem->font();        ui.actFontBold->setChecked(font.bold());    }}void QGuiFileSys::actTabReset_triggered(){    //表格复位    resetTable(10);}void QGuiFileSys::actOpenStm_triggered(){    QString curPath = QDir::currentPath();    //调用打开文件对话框打开一个文件    QString aFileName = QFileDialog::getOpenFileName(this, tr("打开一个文件"), curPath,        "流数据文件(*.stm)");    if (aFileName.isEmpty())        return; //    if (openDataAsStream(aFileName)) //保存为流数据文件        QMessageBox::information(this, "提示消息", "文件已经打开!");}void QGuiFileSys::actSaveStm_triggered(){    //以Qt预定义编码保存数据文件    QString curPath = QDir::currentPath();    QString aFileName = QFileDialog::getSaveFileName(this, tr("选择保存文件"), curPath,        "Qt预定义编码数据文件(*.stm)");    if (aFileName.isEmpty())        return; //    if (saveDataAsStream(aFileName)) //保存为流数据文件        QMessageBox::information(this, "提示消息", "文件已经成功保存!");}void QGuiFileSys::actOpenBin_triggered(){    //打开二进制文件    QString curPath = QDir::currentPath();//系统当前目录    QString aFileName = QFileDialog::getOpenFileName(this, tr("打开一个文件"), curPath,        "二进制数据文件(*.dat)");    if (aFileName.isEmpty())        return; //    if (openBinaryFile(aFileName)) //保存为流数据文件        QMessageBox::information(this, "提示消息", "文件已经打开!");}void QGuiFileSys::actSaveBin_triggered(){    //保存二进制文件    QString curPath = QDir::currentPath();    //调用打开文件对话框选择一个文件    QString aFileName = QFileDialog::getSaveFileName(this, tr("选择保存文件"), curPath,        "二进制数据文件(*.dat)");    if (aFileName.isEmpty())        return; //    if (saveBinaryFile(aFileName)) //保存为流数据文件        QMessageBox::information(this, "提示消息", "文件已经成功保存!");}void QGuiFileSys::actAppend_triggered(){    //添加行    QList aItemList; //容器类    QStandardItem* aItem;    QString str;    for (int i = 0; i < FixedColumnCount - 2; i++)    {        aItem = new QStandardItem("0"); //创建Item        aItemList << aItem;   //添加到容器    }    aItem = new QStandardItem("优"); //创建Item    aItemList << aItem;   //添加到容器    str = theModel->headerData(theModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();    aItem = new QStandardItem(str); //创建Item    aItem->setCheckable(true);    aItem->setEditable(false);    aItemList << aItem;   //添加到容器    theModel->insertRow(theModel->rowCount(), aItemList); //插入一行,需要每个Cell的Item    QModelIndex curIndex = theModel->index(theModel->rowCount() - 1, 0);//创建最后一行的ModelIndex    theSelection->clearSelection();    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);}void QGuiFileSys::actInsert_triggered(){    //插入行    QList aItemList;  //QStandardItem的容器类    QStandardItem* aItem;    QString str;    for (int i = 0; i < FixedColumnCount - 2; i++)    {        aItem = new QStandardItem("0"); //新建一个QStandardItem        aItemList << aItem;//添加到容器类    }    aItem = new QStandardItem("优"); //新建一个QStandardItem    aItemList << aItem;//添加到容器类    str = theModel->headerData(theModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();    aItem = new QStandardItem(str); //创建Item    aItem->setCheckable(true);    aItem->setEditable(false);    aItemList << aItem;//添加到容器类    QModelIndex curIndex = theSelection->currentIndex();    theModel->insertRow(curIndex.row(), aItemList);    theSelection->clearSelection();    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);}void QGuiFileSys::actDelete_triggered(){    //删除行    QModelIndex curIndex = theSelection->currentIndex();    if (curIndex.row() == theModel->rowCount() - 1)//(curIndex.isValid())        theModel->removeRow(curIndex.row());    else    {        theModel->removeRow(curIndex.row());        theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);    }}void QGuiFileSys::actAlignLeft_triggered(){    if (!theSelection->hasSelection())        return;    QModelIndexList selectedIndix = theSelection->selectedIndexes();    QModelIndex aIndex;    QStandardItem* aItem;    for (int i = 0; i < selectedIndix.count(); i++)    {        aIndex = selectedIndix.at(i);        aItem = theModel->itemFromIndex(aIndex);        aItem->setTextAlignment(Qt::AlignLeft);    }}void QGuiFileSys::actAlignCenter_triggered(){    if (!theSelection->hasSelection())        return;    QModelIndexList selectedIndix = theSelection->selectedIndexes();    QModelIndex aIndex;    QStandardItem* aItem;    for (int i = 0; i < selectedIndix.count(); i++)    {        aIndex = selectedIndix.at(i);        aItem = theModel->itemFromIndex(aIndex);        aItem->setTextAlignment(Qt::AlignHCenter);    }}void QGuiFileSys::actAlignRight_triggered(){    if (!theSelection->hasSelection())        return;    QModelIndexList selectedIndix = theSelection->selectedIndexes();    QModelIndex aIndex;    QStandardItem* aItem;    for (int i = 0; i < selectedIndix.count(); i++)    {        aIndex = selectedIndix.at(i);        aItem = theModel->itemFromIndex(aIndex);        aItem->setTextAlignment(Qt::AlignRight);    }}void QGuiFileSys::actFontBold_triggered(bool checked){    if (!theSelection->hasSelection())        return;    QModelIndexList selectedIndix = theSelection->selectedIndexes();    QModelIndex aIndex;    QStandardItem* aItem;    QFont   font;    for (int i = 0; i < selectedIndix.count(); i++)    {        aIndex = selectedIndix.at(i);        aItem = theModel->itemFromIndex(aIndex);        font = aItem->font();        font.setBold(checked);        aItem->setFont(font);    }}

效果如下

35cd0ec5deb41392db8bdb67252cd970.png

使用QDataStream保存文件时使用的数据编码的方式不同,可以保存为两种

1、使用Qt预定义编码保存各种类型数据的文件,定义文件后缀为“.stm”,Qt预定义编码指的是在写入某个数据类型到文件流时,使用Qt预定义的编码。使用Qt预定义编码保存的流文件,某些字节是QDataStream自己写入的,我们并不完全知道文件内每个字节的意义,但是使用QDataStream可以读出相应的数据

2、便准编码数据文件,定义文件后缀为“.dat”,在将数据写到文件时,完全使用数据的二进制原始内容,每个字节都有具体的定义,在读出数据时,只需要根据每个字节的定义读出数据即可

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

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

相关文章

cloud foundry_实际的Reactor操作–检索Cloud Foundry应用程序的详细信息

cloud foundryCF-Java-Client是一个库&#xff0c;可通过程序访问Cloud Foundry Cloud Controller API 。 它建立在Project Reactor之上&#xff0c;它是Reactive Streams规范的实现&#xff0c;并且使用此库在Cloud Foundry环境中做一些实际的事情是一个有趣的练习。 考虑一个…

iis开启php验证码,php结合GD库实现中文验证码的简单方法

前言上一次写了一个常见的验证码&#xff0c;现在玩一下中文的验证码&#xff0c;顺便升级一下写的代码流程基本差不多先看GD库开启了没生成中文5位验证码开始画图画干扰素生成图形完事生成中文验证码//小小心机$hanzi "如果觉得写得还可以的话互相关注报团取暖交流经验来…

Linux 系统关于应该把程序安装在目录 /usr 还是目录 /usr/local 下的思考

对于一个以 LFS(Linux From Scratch 大意&#xff1a;自己做出来的 Linux) 为基础的系统来说&#xff0c;这是一个没有明确答案的问题。什么是 LFS&#xff1f; 在传统的 Unix 系统中&#xff0c;/usr 通常只包含系统发行时自带的程序&#xff0c;而 /usr/local 则是本地系统管…

数据结构设计_合并多种疾病,如何设计数据结构?

如果一个患者合并多种疾病或应用多种药物&#xff0c;如何设计数据结构&#xff1f;例如病史&#xff0c;建议设计成多选题。如果未患病&#xff0c;只需点一次“全无”&#xff0c;操作简单。如果选了全无&#xff0c;其他选框系统自动关闭&#xff0c;就不能再后面的选项了&a…

java ee的小程序_用微服务和容器替换旧版Java EE应用程序服务器

java ee的小程序Lightbend最近对2000多个JVM开发人员进行了一项调查&#xff0c;结果刚刚发布。 开展该调查的目的是发现&#xff1a;发展趋势与IT基础架构趋势之间的相关性&#xff0c;处于数字化转型前沿的组织如何使他们的应用程序现代化以及当今对新兴开发人员技术最为关注…

Linux系统下如何安装JDK?

一、首先下载linux版本jdk 点击进入jdk官网 根据自己的需求&#xff0c;下载不同版本的jdk 2.将下载好的jdk压缩包&#xff0c;通过ftp上传到linux系统的当前用户下&#xff0c;我当前登录的用户为root用户 3.将上传后的jdk&#xff0c;解压到/usr/local/目录下&#xff0c…

php网站模板怎么修改,网站后台模板修改

方法1、首先制作网站背景图片&#xff0c;这个建议找一些大尺寸的图片。(本图仅限测试使用)2、通过FTp工具链接到网站的空间&#xff0c;找到dedecms网站的模版文件templets。找到模版目录下的模版样式文件。如果使用的是默认模版&#xff0c;文件在templets/default/style/ded…

python练手经典100例微盘_Python练手项目实例汇总(附源码下载)

1 #_*_ coding:utf-8 _*_ 2 from tkinter import * 3 importrandom4 importtime5 importtkinter.messagebox6 7 8 #俄罗斯方块界面的高度 9 HEIGHT 20 10 11 #俄罗斯方块界面的宽度 12 WIDTH 10 13 14 ACTIVE 1 15 PASSIVE 016 TRUE 1 17 FALSE 018 19 style [20 [[(0,0),(…

Linux 环境变量设置及查看

文章目录一、设置变量的四种方法&#xff08;一&#xff09;在 /etc/profile 文件中添加变量&#xff08;二&#xff09;在用户目录下的 .bash_profile 文件中添加变量&#xff08;三&#xff09;使用命令 export 声明定义变量&#xff08;四&#xff09;使用命令 declare 声明…

docker 部署java_使用Docker堆栈部署的微服务-WildFly,Java EE和Couchbase

docker 部署java关于微服务的资料很多&#xff0c;只是用谷歌搜索就可以了 &#xff01; 几年前&#xff0c;我在比利时的Devoxx上发表了有关将单片重构为微服务的演讲&#xff0c;它获得了很好的评价&#xff1a; 该博客将展示Docker如何简化微服务的创建和关闭。 该博客中使…

django settings 定义的变量不存在_使用Django部署机器学习模型(1)

介绍机器学习(ML)应用的需求正在不断增长。许多资料显示了如何训练ML算法。然而&#xff0c;ML算法分为两个阶段:训练阶段——在这个阶段&#xff0c;基于历史数据训练ML算法&#xff0c;推理阶段——ML算法被用于计算对未知结果的新数据的预测。商业利益就处于推理阶段&#x…

php系统函数区分大小写,php函数名区分大小写吗?

PHP对大小写敏感问题的处理比较乱&#xff0c;写代码时可能偶尔出问题&#xff0c;所以下面本篇文章就来总结一下。有一定的参考价值&#xff0c;有需要的朋友可以参考一下&#xff0c;希望对你有所帮助。但我不是鼓励大家去用这些规则。推荐大家始终坚持“大小写敏感”&#x…

提取javadoc_使用JavaParser从源文件中提取JavaDoc文档

提取javadoc很多人正在使用JavaParser实现最不同的目标。 其中之一是提取文档。 在这篇简短的文章中&#xff0c;我们将看到如何打印与类或接口关联的所有JavaDoc注释。 可以在GitHub上找到代码&#xff1a; https : //github.com/ftomassetti/javadoc-extractor 获取类的所有…

python条形堆积图_python – 使用DataFrame.plot显示堆积条形图中...

您可以使用plt.text根据数据将信息放在位置. 但是,如果你有非常小的条形,可能需要一些调整才能看起来很完美. df_total df[Total Cost] df df.iloc[:, 0:4] df.plot(x Airport, kindbarh,stacked True, title Breakdown of Costs, mark_right True) df_rel df[df.column…

dmc matlab程序,matlab编的DMC程序.doc

matlab编的DMC程序clear all;% close all;%系统模型建立num[0.8];den[225 1];[a,b,c,d]tf2ss(num,den);% step(num,den);Ts30;lambda60;[ad,bd,cd,dd]c2dt(a,b,c,Ts,lambda);[numd,dend]ss2tf(ad,bd,cd,dd);[a,x]dstep(ad,bd,cd,dd);P10;M5;N50;%动态矩阵Afor i1:Pfor j1:Mif j…

mega2560单片机开发_[MEGA DEAL] Ultimate Java开发和认证指南(59%折扣)

mega2560单片机开发通过介绍世界上最受欢迎的编程语言之一掌握Java编程概念 嘿&#xff0c;怪胎&#xff0c; 本周&#xff0c;在我们的JCG Deals商店中 &#xff0c;我们提供了一个极端的报价 。 我们提供的《 Ultimate Java Development and Certification Guide 》 仅售2…

MySQL使用规范_心得总结

文章目录命名规范数据库基本设计规范数据库字段设计规范索引设计规范常见索引列建议数据库开发规范数据库操作行为规范命名规范 1.所有数据库对象名称必须使用小写字母并用下划线分割 2.禁止使用 MySQL 保留关键字&#xff0c;如果表名中包含关键字查询时&#xff0c;需要使用…

java界面 文件选择器_掌握java技术 必备java工具应用知识

在现如今的互联网时代里&#xff0c;Java无疑是一种极为流行的开发语言&#xff0c;无论是程序界还是整个互联网行业势必带来很大的影响。不管是人才需求还是薪资水平上&#xff0c;Java的发展前景都是很乐观的。关于Java的一些常用的工具&#xff0c;也是需要我们不断去掌握和…

php制作404,利用thinkphp怎么制作一个404跳转页面

利用thinkphp怎么制作一个404跳转页面发布时间&#xff1a;2020-12-14 15:46:55来源&#xff1a;亿速云阅读&#xff1a;97作者&#xff1a;Leah本篇文章给大家分享的是有关利用thinkphp怎么制作一个404跳转页面&#xff0c;小编觉得挺实用的&#xff0c;因此分享给大家学习&am…

junit 验证日志输出_JUnit规则–引发异常时执行附加验证

junit 验证日志输出在本文中&#xff0c;我将快速向您展示如果您需要解决以下挑战&#xff0c;那么JUnit规则有多方便 一个方法可以捕获异常&#xff0c;并且必须在抛出或引发包装异常之前执行一些额外的任务。 调用额外任务和引发的异常应通过单元测试进行验证。 这意味着你…