qt 读文件修改并保存

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QFileDialog>

// QFileDialog
//  QFile
//  Stream:    QTextStream        QDataStream
//  QTextEdit

//  xml  ini  json

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect( ui->openButton, SIGNAL(clicked(bool)),
             this, SLOT(onOpenButtonClicked()) );
    connect( ui->saveButton, SIGNAL(clicked(bool)),
             this, SLOT(onSaveButtonClicked()) );
}

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

// open file  ->  read file -> textEdit->close file
void MainWindow::onOpenButtonClicked()
{
//   QFileDialog dlg;
//    int ret = dlg.exec();
//    if( ret == QDialog::Accepted ){
//        ui->lineEdit->setText( dlg.selectedFiles().at(0));
//    }
    QString filename = QFileDialog::getOpenFileName(this,
                                                    "open source file",
                                                    "/home/lesson/39th/qt/5th",

                                                    tr("CPP *.cpp"));
    ui->lineEdit->setText(filename);

    QFile file(filename);
    if(    file.open( QIODevice::ReadWrite ) ){
            QTextStream in(&file);
            while( in.atEnd() == false){
                QString str = in.readLine();
                ui->textEdit->append(str);
            }
    }
    file.close();
}

// open file->  textEdit-> save file -> close file
void MainWindow::onSaveButtonClicked()
{
//    QString filename = QFileDialog::getSaveFileName(this,
//                                                    "save source file",
//                                                    "/home/lesson/39th/qt/5th/",
//                                                    tr("CPP *.cpp"));

    QString filename = QFileDialog::getSaveFileName(this,
                                                    "save source file",
                                                    NULL,
                                                    tr("*"));
    ui->lineEdit->setText(filename);

    QFile file(filename);
    if(    file.open( QIODevice::ReadWrite ) ){
            QTextStream out(&file);
            out << ui->textEdit->toPlainText();
    }
    file.close();

}

 

发布了12 篇原创文章 · 获赞 3 · 访问量 1375
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览