您的位置:首页 > 编程语言 > Qt开发

Qt打开读取和保存写入文件

2016-11-29 19:25 543 查看
打开
在头文件mainwindow.h中添加打开文件需要的包

#include<QMessageBox>
#include<QDebug>
#include<QMainWindow>
#include<QFile>
#include<QFileDialog>
#include<QDir>
#include<QTextStream>

并且添加私有信号槽

private slots:
     void openFileSlot();

在mainwindow.cpp源文件中添加打开文件函数

void MainWindow::openFileSlot()
{
     //获取文件名称
     QString fileName = QFileDialog::getOpenFileName(this,"OpenFile",QDir::currentPath());
     if(fileName.isEmpty())
     {
          QMessageBox::information(this,"Error","Please select a txt");
          return;
     }
     else
     {
          QFile *file = new QFile;
          file->setFileName(fileName);//新建一个文件对象,并且把它设置为上面获取的文件
          bool ok=file->open(QIODevice::ReadOnly);//设置打开模式

          if(ok)//如果可以打开
          {
               //将文件与文本流相关联
               QTextStream in(file);
               ui->textEdit->setText(in.readAll());//读取该文件的所有内容
               file->close();//关闭文件
               delete file();//释放文件进程
           }
           else
           {
               QMessageBox::information(this,"Error Box","FileOpen Error"+file->errorString());
           }
}

在MainWindow构造函数中添加信号与槽的连接信息

QObject::connect(ui->openAction,SIGNAL(triggered()),this,SLOT(openFileSlot()));
保存
保存就是打开文件的逆过程
同样,在mainwindow.h添加私有信号槽

private slots:
     void saveFileSlot();

在mainwindow.cpp中添加保存的函数

void MainWindow::saveFileSlot()
{
    QString filename = QFileDialog::getSaveFileName(this,"Save File","D:\\");//获取需要保存成的文件名
    if(filename.isEmpty())
    {
        QMessageBox::information(this,"ErrorBox","Please input the filename");
        return;
    }
    else
    {
        QFile *file = new QFile;
        file->setFileName(filename);
        bool ok = file->open(QIODevice::WriteOnly)

        if(ok)
        {
            QTextStream out(file);
            out<<ui->textEdit->toPlainText(); //转化成纯文本
            file->close();
            delete(file);
        }
        else
        {
            QMessageBox::information(this,"ErrorBox","file fail to save")
        }
    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐