QT以文本流形式读写文件操作

ui文件为两个按钮,一个文本编辑区,按钮控制读写操作,文本框显示文本内容

#include "mywidget.h"
#include "ui_mywidget.h"
#include 
MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);
    ui->textEdit->hide();
}

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

void MyWidget::on_pushButton_clicked()
{
    QString path = QFileDialog::getSaveFileName(this,"保存文件","/myfile/code/qt/","txt (*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file(path);
        bool ret = file.open(QIODevice::WriteOnly);
        if(ret == true)
        {
           QTextStream stream(&file);
           //可以指定编码类型
           stream.setCodec("UTF-8");
           //文件写入
           stream<textEdit->show();
    QString path = QFileDialog::getOpenFileName(this,"打开文件","/myfile/code/qt/","txt (*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file(path);
        bool ret = file.open(QIODevice::ReadOnly);
        if(ret == true)
        {
            //关联文件
            QTextStream stream(&file);
            //读取文件
            QByteArray array = file.readAll();
            //文件显示
            ui->textEdit->setText(array);
            file.close();
        }
    }
}

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include 
#include 
#include 
#include 
namespace Ui {
class MyWidget;
}

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();

private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();

private:
    Ui::MyWidget *ui;
};

#endif // MYWIDGET_H

你可能感兴趣的:(个人笔记,随笔,Qt,c++)