QT实现文件读写

1.widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
Q_OBJECT

public:
Widget(QWidget *parent = nullptr);
~Widget();

private slots:
void on_pushButtonRead_clicked();

void on_pushButtonWrite_clicked();

private:
Ui::Widget *ui;
};
#endif // WIDGET_H

2.widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
//文件对话框

Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}

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

//读文件
void Widget::on_pushButtonRead_clicked()
{
QString path=QFileDialog::getOpenFileName(this,"Open File","../","TXT (*.txt)");
if(path.isEmpty()==false)
{
QFile file(path);
//打开文件,以只读的方式
bool isopen=file.open(QIODevice::ReadOnly);
//如果打开成功,读文件
if( isopen==true )
{
QByteArray msg=file.readAll();
ui->textEdit->setText(msg);
}
file.close();
}

}

//写文件
void Widget::on_pushButtonWrite_clicked()
{
QString path1=QFileDialog::getSaveFileName(this,"save file","../","TXT (*.txt)");
if(path1.isEmpty()==false)
{
QFile filewrite;
filewrite.setFileName(path1);
bool iswrite=filewrite.open(QIODevice::WriteOnly);
if(iswrite==true)
{
QString str=ui->textEdit->toPlainText();
filewrite.write(str.toUtf8());
}
filewrite.close();
}

}

3.结果显示

发表评论

相关文章